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

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



답변

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

자바 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고가의 작가 (예 :)에게는를 사용하는 것이 좋습니다 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();
        }
    }
}


답변

Kip의 답변 을 약간 확장하려면 다음 과 같이 파일에 새 줄 을 추가하여 존재하지 않는 경우 파일을 만드는 간단한 Java 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기록 과부하 라인 (A와 유사한 즉, 파일에 텍스트를 println명령). 끝에 텍스트를 쓰려면 (예 : print명령 과 유사 ) Files.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);