简体   繁体   English

刷新并关闭后,BufferedWriter不会写入文件

[英]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. 我已经确保在读取文件之前调用了flush()和close()方法,但即使那样也没有帮助。

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. 每次创建新的TestWrite_Read()您都在打开文件进行输出,从而清空文件。

Don't do that. 不要那样做 If you want to just read from the file, don't open it for output first. 如果您只想读取文件,请不要先打开文件以进行输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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