back end/java

How to append text to an existing file in Java?

노루아부지 2023. 1. 1. 00:36
반응형

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
반응형
loading