简体   繁体   中英

BufferedWriter does not write to file after flush and close

I have following sample application in which I write to a file and immediately after closing the writer, I try to read from the file but to my surprise nothing is written to file.

I have made sure that flush() and close() methods are invoked before i read the file but even that is not helping me here.

Can some one help me understand why following code is not working.

public class TestWrite_Read {

private File file;
private Writer writer;

public TestWrite_Read() {
    file = new File("E:\\temp\\test.txt");
    try {
        writer = new BufferedWriter(new FileWriter(file));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) throws  Exception {
    new TestWrite_Read().write();
    new TestWrite_Read().read();
}

private void read() throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader(file));
    System.out.println("reader.readLine() = " + reader.readLine());
    reader.close();
}

private void write() throws Exception {
    writer.write(String.valueOf(104));
    writer.flush();
    writer.close();
}}

Every time you create a new TestWrite_Read() you are opening the file for output, which empties it.

Don't do that. If you want to just read from the file, don't open it for output first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM