Search code examples
javabufferedreaderbufferedwriterwriterreader

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();
}}

Solution

  • 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.