문제

I am having my first go at trying to write my own txt to a a file ,in a specific directory. The test.mod file is correctly placed ,but when I open up the file it is empty and contains no text. What am I missing here?

   public static void main(String[] args) {
    String pad = "C:\\Users\\Bernard\\Documents\\Paradox Interactive";
    File bestand = new File(pad + "\\test.mod");
    try {
        BufferedWriter pen = new BufferedWriter(new FileWriter(bestand));
        pen.write("line1");
        pen.write("line2");

    }catch(IOException e){            
    }
}

Thank you for your time

도움이 되었습니까?

해결책

When you write to a BufferedWriter you are (potentially) writing to an in-memory buffer, and you must flush() your writes to make sure they reach the disk. close() would also implicitly call flush() on any reasonable implementation, but it isn't considered a good practice to rely on it:

public static void main(String[] args) {
    String pad = "C:\\Users\\Bernard\\Documents\\Paradox Interactive";
    File bestand = new File(pad + "\\test.mod");
    BufferedWriter pen = null;
    try {
        pen = new BufferedWriter(new FileWriter(bestand));
        pen.write("line1");
        pen.write("line2");
        pen.flush();
    }catch(IOException e){
        // Probably should have some treatment here too
    }
    finally {
        if (pen != null) {
            pen.close();
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top