Programing

Java에서 기존 파일에 텍스트를 추가하는 방법

crosscheck 2020. 10. 2. 21:32
반응형

Java에서 기존 파일에 텍스트를 추가하는 방법


Java의 기존 파일에 반복적으로 텍스트를 추가해야합니다. 어떻게하나요?


로깅 목적으로이 작업을 수행하고 있습니까? 그렇다면이를 위한 여러 라이브러리가 있습니다. 가장 인기있는 두 가지는 Log4jLogback 입니다.

Java 7 이상

이 작업을 한 번만 수행해야하는 경우 Files 클래스를 사용하면이 작업을 쉽게 수행 할 수 있습니다.

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

주의 : 위의 접근 방식은 NoSuchFileException파일이 아직 존재하지 않는 경우에 발생합니다. 또한 자동으로 줄 바꿈을 추가하지 않습니다 (텍스트 파일에 추가 할 때 자주 원함). Steve Chambers의 답변Files수업에서 이것을 어떻게 할 수 있는지를 다룹니다 .

그러나 동일한 파일에 여러 번 쓰는 경우 위의 방법은 디스크의 파일을 여러 번 열고 닫아야하므로 작업이 느립니다. 이 경우 버퍼링 된 작성자가 더 좋습니다.

try(FileWriter fw = new FileWriter("myfile.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

메모:

  • FileWriter생성자 의 두 번째 매개 변수 는 새 파일을 작성하는 대신 파일에 추가하도록 지시합니다. (파일이없는 경우 생성됩니다.)
  • BufferedWriter고가의 작성자 (예 :)에는 a를 사용하는 것이 좋습니다 FileWriter.
  • 를 사용 하면에서 익숙한 구문에 PrintWriter액세스 할 println수 있습니다 System.out.
  • 그러나 BufferedWriterPrintWriter래퍼가 반드시 필요한 것은 아닙니다.

이전 자바

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

예외 처리

이전 Java에 대한 강력한 예외 처리가 필요한 경우 매우 장황합니다.

FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt", true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(bw != null)
            bw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(fw != null)
            fw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
}

추가를 위해 fileWriter으로 설정된 플래그와 함께 사용할 수 있습니다 true.

try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}

try / catch 블록에 대한 모든 답변에 finally 블록에 포함 된 .close () 조각이 있어야하지 않습니까?

표시된 답변의 예 :

PrintWriter out = null;
try {
    out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
} finally {
    if (out != null) {
        out.close();
    }
} 

또한 Java 7부터 try-with-resources 문을 사용할 수 있습니다 . 선언 된 리소스를 닫는 데 finally 블록이 필요하지 않습니다. 자동으로 처리되고 덜 장황하기 때문입니다.

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
}

편집 -Apache Commons 2.1부터 올바른 방법은 다음과 같습니다.

FileUtils.writeStringToFile(file, "String to append", true);

마지막으로 파일을 올바르게 닫는 것을 포함하도록 @Kip의 솔루션을 조정했습니다.

public static void appendToFile(String targetFile, String s) throws IOException {
    appendToFile(new File(targetFile), s);
}

public static void appendToFile(File targetFile, String s) throws IOException {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new BufferedWriter(new FileWriter(targetFile, true)));
        out.println(s);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}


약간의 확장하려면 킵의 대답은 여기에 추가하는 간단한 자바 7+ 방법으로 새로운 라인 , 파일에를 가 존재하지 않는 경우는, 작성 :

try {
    final Path path = Paths.get("path/to/filename.txt");
    Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
        Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
    // Add your own exception handling...
}

참고 :의 내용은 파일에 텍스트 Files.write 을 쓰는 오버로드를 사용 합니다 (예 : 명령 과 유사 ). 끝까지 텍스트를 쓰려면 (예 : 명령 과 유사 ) 바이트 배열 (예 :)을 전달 하는 대체 오버로드를 사용할 수 있습니다 .printlnprintFiles.write"mytext".getBytes(StandardCharsets.UTF_8)


모든 시나리오에서 스트림이 제대로 닫혀 있는지 확인하십시오.

이러한 답변 중 오류가 발생했을 때 파일 핸들을 열어 두는 것은 약간 놀라운 일입니다. 대답 https://stackoverflow.com/a/15053443/2498188 은 돈에 있지만 BufferedWriter()던질 수 없기 때문 입니다. 가능한 경우 예외가 FileWriter개체를 열어 둡니다 .

BufferedWriter()던질 수 있는지 상관하지 않는 더 일반적인 방법은 다음과 같습니다.

  PrintWriter out = null;
  BufferedWriter bw = null;
  FileWriter fw = null;
  try{
     fw = new FileWriter("outfilename", true);
     bw = new BufferedWriter(fw);
     out = new PrintWriter(bw);
     out.println("the text");
  }
  catch( IOException e ){
     // File writing/opening failed at some stage.
  }
  finally{
     try{
        if( out != null ){
           out.close(); // Will close bw and fw too
        }
        else if( bw != null ){
           bw.close(); // Will close fw too
        }
        else if( fw != null ){
           fw.close();
        }
        else{
           // Oh boy did it fail hard! :3
        }
     }
     catch( IOException e ){
        // Closing the file writers failed for some obscure reason
     }
  }

편집하다:

Java 7에서 권장되는 방법은 "리소스로 시도"를 사용하고 JVM이 처리하도록하는 것입니다.

  try(    FileWriter fw = new FileWriter("outfilename", true);
          BufferedWriter bw = new BufferedWriter(fw);
          PrintWriter out = new PrintWriter(bw)){
     out.println("the text");
  }  
  catch( IOException e ){
      // File writing/opening failed at some stage.
  }

Java-7에서는 다음과 같은 종류의 작업도 수행 할 수 있습니다.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

// ---------------------

Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
    Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);

자바 7 이상

나는 평범한 자바의 팬이기 때문에 겸손한 의견으로 앞서 언급 한 답변의 조합이라고 제안합니다. 파티에 늦었을 수도 있습니다. 다음은 코드입니다.

 String sampleText = "test" +  System.getProperty("line.separator");
 Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8), 
 StandardOpenOption.CREATE, StandardOpenOption.APPEND);

파일이 존재하지 않으면 생성하고 이미 존재하는 경우 기존 파일에 sampleText추가 합니다. 이것을 사용하면 불필요한 라이브러리를 클래스 경로에 추가하지 않아도됩니다.


이것은 한 줄의 코드로 수행 할 수 있습니다. 도움이 되었기를 바랍니다 :)

Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);

java.nio 사용. java.nio.file과 함께 파일 . StandardOpenOption

    PrintWriter out = null;
    BufferedWriter bufWriter;

    try{
        bufWriter =
            Files.newBufferedWriter(
                Paths.get("log.txt"),
                Charset.forName("UTF8"),
                StandardOpenOption.WRITE, 
                StandardOpenOption.APPEND,
                StandardOpenOption.CREATE);
        out = new PrintWriter(bufWriter, true);
    }catch(IOException e){
        //Oh, no! Failed to create PrintWriter
    }

    //After successful creation of PrintWriter
    out.println("Text to be appended");

    //After done writing, remember to close!
    out.close();

이렇게하면 매개 변수 BufferedWriter를 허용 하는 using Files 가 생성되고 결과에서 StandardOpenOption자동 플러시 PrintWriter가 생성 BufferedWriter됩니다. PrintWriterprintln()메서드를 호출하여 파일에 쓸 수 있습니다.

StandardOpenOption이 코드에 사용 된 매개 변수 : 만 파일에 추가, 쓰기 위해 파일을 열고, 존재하지 않는 경우 파일을 작성합니다.

Paths.get("path here")로 바꿀 수 있습니다 new File("path here").toPath(). 그리고 Charset.forName("charset name")원하는대로 수정할 수 있습니다 Charset.


나는 단지 작은 세부 사항을 추가합니다.

    new FileWriter("outfilename", true)

2.nd 매개 변수 (true)는 추가 가능 ( http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html ) 이라는 기능 (또는 인터페이스 )입니다. 특정 파일 / 스트림의 끝에 일부 콘텐츠를 추가 할 수 있습니다. 이 인터페이스는 Java 1.5부터 구현되었습니다. 이 인터페이스가있는 각 객체 (예 : BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer )는 콘텐츠를 추가하는 데 사용할 수 있습니다.

즉, gzip 파일 또는 http 프로세스에 일부 콘텐츠를 추가 할 수 있습니다.


Guava를 사용한 샘플 :

File to = new File("C:/test/test.csv");

for (int i = 0; i < 42; i++) {
    CharSequence from = "some string" + i + "\n";
    Files.append(from, to, Charsets.UTF_8);
}

bufferFileWriter.append로 시도하면 나와 함께 작동합니다.

FileWriter fileWriter;
try {
    fileWriter = new FileWriter(file,true);
    BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
    bufferFileWriter.append(obj.toJSONString());
    bufferFileWriter.newLine();
    bufferFileWriter.close();
} catch (IOException ex) {
    Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}

    String str;
    String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw = new PrintWriter(new FileWriter(path, true));

    try 
    {
       while(true)
        {
            System.out.println("Enter the text : ");
            str = br.readLine();
            if(str.equalsIgnoreCase("exit"))
                break;
            else
                pw.println(str);
        }
    } 
    catch (Exception e) 
    {
        //oh noes!
    }
    finally
    {
        pw.close();         
    }

이것은 당신이 원하는 것을 할 것입니다 ..


try-with-resources를 사용하는 것이 더 나은 모든 pre-java 7 마침내 비즈니스

static void appendStringToFile(Path file, String s) throws IOException  {
    try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        out.append(s);
        out.newLine();
    }
}

Java 7 이상을 사용하고 있으며 파일에 추가 (추가) 할 내용도 알고 있다면 NIO 패키지 newBufferedWriter 메소드를 사용할 수 있습니다 .

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

몇 가지주의 할 점이 있습니다.

  1. charset 인코딩을 지정하는 것은 항상 좋은 습관이며 클래스에 상수가 있습니다 StandardCharsets.
  2. 이 코드는 try-with-resource시도 후 리소스가 자동으로 닫히는 문을 사용 합니다.

OP는 요청하지 않았지만 특정 키워드가있는 행을 검색하려는 경우를 대비 confidential하여 Java에서 스트림 API를 사용할 수 있습니다.

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Writer {


    public static void main(String args[]){
        doWrite("output.txt","Content to be appended to file");
    }

    public static void doWrite(String filePath,String contentToBeAppended){

       try(
            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw)
          )
          {
            out.println(contentToBeAppended);
          }  
        catch( IOException e ){
        // File writing/opening failed at some stage.
        }

    }

}

FileOutputStream stream = new FileOutputStream(path, true);
try {

    stream.write(

        string.getBytes("UTF-8") // Choose your encoding.

    );

} finally {
    stream.close();
}

그런 다음 업스트림 어딘가에서 IOException을 포착하십시오.


프로젝트 어디에서나 함수를 만들고 필요할 때마다 해당 함수를 호출하기 만하면됩니다.

여러분은 여러분이 비동기 적으로 호출하지 않는 활성 스레드를 호출하고 있다는 사실을 기억해야합니다. 제대로 수행하려면 5 ~ 10 페이지 정도면 좋을 것입니다. 프로젝트에 더 많은 시간을 할애하고 이미 작성된 내용은 잊어 버리십시오. 정확히

    //Adding a static modifier would make this accessible anywhere in your app

    public Logger getLogger()
    {
       return java.util.logging.Logger.getLogger("MyLogFileName");
    }
    //call the method anywhere and append what you want to log 
    //Logger class will take care of putting timestamps for you
    //plus the are ansychronously done so more of the 
    //processing power will go into your application

    //from inside a function body in the same class ...{...

    getLogger().log(Level.INFO,"the text you want to append");

    ...}...
    /*********log file resides in server root log files********/

세 번째 코드는 실제로 텍스트를 추가하기 때문에 두 줄의 코드입니다. :피


도서관

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

암호

public void append()
{
    try
    {
        String path = "D:/sample.txt";

        File file = new File(path);

        FileWriter fileWriter = new FileWriter(file,true);

        BufferedWriter bufferFileWriter  = new BufferedWriter(fileWriter);

        fileWriter.append("Sample text in the file to append");

        bufferFileWriter.close();

        System.out.println("User Registration Completed");

    }catch(Exception ex)
    {
        System.out.println(ex);
    }
}

다음을 시도해 볼 수도 있습니다.

JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file



try 
{
    RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
    long length = raf.length();
    //System.out.println(length);
    raf.setLength(length + 1); //+ (integer value) for spacing
    raf.seek(raf.length());
    raf.writeBytes(Content);
    raf.close();
} 
catch (Exception e) {
    //any exception handling method of ur choice
}

FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);

true이면 기존 파일에 데이터를 추가 할 수 있습니다. 우리가 쓰면

FileOutputStream fos = new FileOutputStream("File_Name");

기존 파일을 덮어 씁니다. 따라서 첫 번째 접근 방식으로 이동하십시오.


아파치 커먼즈 프로젝트를 제안 할 수 있습니다 . 이 프로젝트는 이미 필요한 작업을 수행하기위한 프레임 워크를 제공합니다 (예 : 유연한 컬렉션 필터링).


다음 방법을 사용하면 일부 파일에 텍스트를 추가 할 수 있습니다.

private void appendToFile(String filePath, String text)
{
    PrintWriter fileWriter = null;

    try
    {
        fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
                filePath, true)));

        fileWriter.println(text);
    } catch (IOException ioException)
    {
        ioException.printStackTrace();
    } finally
    {
        if (fileWriter != null)
        {
            fileWriter.close();
        }
    }
}

또는 다음을 사용하십시오 FileUtils.

public static void appendToFile(String filePath, String text) throws IOException
{
    File file = new File(filePath);

    if(!file.exists())
    {
        file.createNewFile();
    }

    String fileContents = FileUtils.readFileToString(file);

    if(file.length() != 0)
    {
        fileContents = fileContents.concat(System.lineSeparator());
    }

    fileContents = fileContents.concat(text);

    FileUtils.writeStringToFile(file, fileContents);
}

효율적이지는 않지만 잘 작동합니다. 줄 바꿈이 올바르게 처리되고 아직 파일이없는 경우 새 파일이 생성됩니다.


이 코드는 귀하의 필요를 충족시킵니다.

   FileWriter fw=new FileWriter("C:\\file.json",true);
   fw.write("ssssss");
   fw.close();

특정 줄에 일부 텍스트추가 하려면 먼저 전체 파일을 읽고 원하는 곳에 텍스트를 추가 한 다음 아래 코드와 같이 모든 것을 덮어 쓸 수 있습니다.

public static void addDatatoFile(String data1, String data2){


    String fullPath = "/home/user/dir/file.csv";

    File dir = new File(fullPath);
    List<String> l = new LinkedList<String>();

    try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
        String line;
        int count = 0;

        while ((line = br.readLine()) != null) {
            if(count == 1){
                //add data at the end of second line                    
                line += data1;
            }else if(count == 2){
                //add other data at the end of third line
                line += data2;
            }
            l.add(line);
            count++;
        }
        br.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
    createFileFromList(l, dir);
}

public static void createFileFromList(List<String> list, File f){

    PrintWriter writer;
    try {
        writer = new PrintWriter(f, "UTF-8");
        for (String d : list) {
            writer.println(d.toString());
        }
        writer.close();             
    } catch (FileNotFoundException | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

내 대답 :

JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";

try 
{
    RandomAccessFile random = new RandomAccessFile(file, "rw");
    long length = random.length();
    random.setLength(length + 1);
    random.seek(random.length());
    random.writeBytes(Content);
    random.close();
} 
catch (Exception exception) {
    //exception handling
}

/**********************************************************************
 * it will write content to a specified  file
 * 
 * @param keyString
 * @throws IOException
 *********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
    // For output to file
    File a = new File(textFilePAth);

    if (!a.exists()) {
        a.createNewFile();
    }
    FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(keyString);
    bw.newLine();
    bw.close();
}// end of writeToFile()

다음 코드를 사용하여 파일에 내용을 추가 할 수 있습니다.

 String fileName="/home/shriram/Desktop/Images/"+"test.txt";
  FileWriter fw=new FileWriter(fileName,true);    
  fw.write("here will be you content to insert or append in file");    
  fw.close(); 
  FileWriter fw1=new FileWriter(fileName,true);    
 fw1.write("another content will be here to be append in the same file");    
 fw1.close(); 

1.7 접근 :

void appendToFile(String filePath, String content) throws IOException{

    Path path = Paths.get(filePath);

    try (BufferedWriter writer = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.APPEND)) {
        writer.newLine();
        writer.append(content);
    }

    /*
    //Alternative:
    try (BufferedWriter bWriter = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.WRITE, StandardOpenOption.APPEND);
            PrintWriter pWriter = new PrintWriter(bWriter)
            ) {
        pWriter.println();//to have println() style instead of newLine();   
        pWriter.append(content);//Also, bWriter.append(content);
    }*/
}

참고 URL : https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java

반응형