Program Tip

Java의 기존 파일에 새 텍스트 줄을 추가하는 방법은 무엇입니까?

programtip 2020. 10. 9. 12:16
반응형

Java의 기존 파일에 새 텍스트 줄을 추가하는 방법은 무엇입니까?


이 질문에 이미 답변이 있습니다.

해당 파일의 현재 정보를 지우지 않고 기존 파일에 새 줄을 추가하고 싶습니다. 요컨대, 현재 시간을 사용하는 방법론은 다음과 같습니다.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;

Writer output;
output = new BufferedWriter(new FileWriter(my_file_name));  //clears file every time
output.append("New Line!");
output.close();

위 줄의 문제는 단순히 기존 파일의 모든 내용을 지우고 새 줄 텍스트를 추가한다는 것입니다.

지우거나 바꾸지 않고 파일 내용 끝에 텍스트를 추가하고 싶습니다.


FileWriter(String fileName, boolean append)생성자 를 사용하여 수행 할 수있는 추가 모드에서 파일을 열어야합니다 .

output = new BufferedWriter(new FileWriter(my_file_name, true));

트릭을해야한다


의 솔루션 FileWriter은 작동하지만 출력 인코딩을 지정할 수 없습니다.이 경우 컴퓨터의 기본 인코딩이 사용되며 일반적으로 UTF-8이 아닙니다!

따라서 기껏해야 사용 FileOutputStream:

    Writer writer = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(file, true), "UTF-8"));

시도 : " \ r \ n "

Java 7 예 :

// append = true
try(PrintWriter output = new PrintWriter(new FileWriter("log.txt",true))) 
{
    output.printf("%s\r\n", "NEWLINE");
} 
catch (Exception e) {}

Java 7 부터 :

시작 부분에 줄 구분 기호를 포함하는 경로 및 문자열을 정의합니다.

Path p = Paths.get("C:\\Users\\first.last\\test.txt");
String s = System.lineSeparator() + "New Line!";

그런 다음 다음 방법 중 하나를 사용할 수 있습니다.

  1. 사용 Files.write(작은 파일) :

    try {
        Files.write(p, s.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
        System.err.println(e);
    }
    
  2. 사용 Files.newBufferedWriter(텍스트 파일) :

    try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) {
        writer.write(s);
    } catch (IOException ioe) {
        System.err.format("IOException: %s%n", ioe);
    }
    
  3. 사용 Files.newOutputStream( java.ioAPI 와 상호 운용 가능 ) :

    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) {
        out.write(s.getBytes());
    } catch (IOException e) {
        System.err.println(e);
    }
    
  4. 사용 Files.newByteChannel(랜덤 액세스 파일) :

    try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    
  5. 사용 FileChannel.open(랜덤 액세스 파일) :

    try (FileChannel sbc = FileChannel.open(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    

이러한 방법에 대한 자세한 내용은 Oracle의 자습서 에서 찾을 수 있습니다 .


In case you are looking for a cut and paste method that creates and writes to a file, here's one I wrote that just takes a String input. Remove 'true' from PrintWriter if you want to overwrite the file each time.

private static final String newLine = System.getProperty("line.separator");

private synchronized void writeToFile(String msg)  {
    String fileName = "c:\\TEMP\\runOutput.txt";
    PrintWriter printWriter = null;
    File file = new File(fileName);
    try {
        if (!file.exists()) file.createNewFile();
        printWriter = new PrintWriter(new FileOutputStream(fileName, true));
        printWriter.write(newLine + msg);
    } catch (IOException ioex) {
        ioex.printStackTrace();
    } finally {
        if (printWriter != null) {
            printWriter.flush();
            printWriter.close();
        }
    }
}

On line 2 change new FileWriter(my_file_name) to new FileWriter(my_file_name, true) so you're appending to the file rather than overwriting.

File f = new File("/path/of/the/file");
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
            bw.append(line);
            bw.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

You can use the FileWriter(String fileName, boolean append) constructor if you want to append data to file.

Change your code to this:

output = new BufferedWriter(new FileWriter(my_file_name, true));

From FileWriter javadoc:

Constructs a FileWriter object given a file name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

참고URL : https://stackoverflow.com/questions/4614227/how-to-add-a-new-line-of-text-to-an-existing-file-in-java

반응형