Java의 기존 파일에 새 텍스트 줄을 추가하는 방법은 무엇입니까?
이 질문에 이미 답변이 있습니다.
- Java 30 답변 에서 기존 파일에 텍스트를 추가하는 방법
해당 파일의 현재 정보를 지우지 않고 기존 파일에 새 줄을 추가하고 싶습니다. 요컨대, 현재 시간을 사용하는 방법론은 다음과 같습니다.
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!";
그런 다음 다음 방법 중 하나를 사용할 수 있습니다.
사용
Files.write
(작은 파일) :try { Files.write(p, s.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { System.err.println(e); }
사용
Files.newBufferedWriter
(텍스트 파일) :try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) { writer.write(s); } catch (IOException ioe) { System.err.format("IOException: %s%n", ioe); }
사용
Files.newOutputStream
(java.io
API 와 상호 운용 가능 ) :try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) { out.write(s.getBytes()); } catch (IOException e) { System.err.println(e); }
사용
Files.newByteChannel
(랜덤 액세스 파일) :try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) { sbc.write(ByteBuffer.wrap(s.getBytes())); } catch (IOException e) { System.err.println(e); }
사용
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.
'Program Tip' 카테고리의 다른 글
열거 형의 JPA 맵 컬렉션 (0) | 2020.10.09 |
---|---|
2D 배열의 크기는 어떻게 찾습니까? (0) | 2020.10.09 |
Spring Cache @Cacheable-동일한 Bean의 다른 메소드에서 호출하는 동안 작동하지 않음 (0) | 2020.10.09 |
Ubuntu의 php 5.6에 php-zip 설치 (0) | 2020.10.09 |
내 info.plist 및 .pch 파일이 어디에 있는지 Xcode에 알리는 방법 (0) | 2020.10.09 |