반응형
java에서 파일을 열어서 그 파일에 내용을 추가하는 방법은 다음과 같습니다.
이 방법은 java 7 이후 버전에서 사용 가능합니다.
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
}
만약 java6이라면 방법은 다음과 같습니다.
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
}
}
출처: https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java
728x90
반응형
'back end > java' 카테고리의 다른 글
[java] Get the "last modified" date from a file (0) | 2023.01.07 |
---|---|
ClassNotFoundException: JAXBException 해결 방법 (0) | 2023.01.06 |
java - Find a line in a file and remove it (0) | 2023.01.01 |
[Spring] MariaDB log4jdbc Cannot create JDBC driver error (2) | 2022.12.22 |
spring 에서 cron scheduler 를 disable 하는 방법 (0) | 2022.12.21 |