为什么BufferedWriter不写入文件? [英] Why is BufferedWriter not writing to file?

查看:733
本文介绍了为什么BufferedWriter不写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

I have this code:

    String[] strings = {"Hi" , "You", "He", "They", "Tetrabenzene", "Caaorine", "Calorine"};

    File file = new File("G:\\words.txt");
    FileWriter fWriter;
    BufferedWriter bWriter;

    try {
        if((file.exists())) {
            file.createNewFile();
        }
        fWriter = new FileWriter(file.getAbsoluteFile(), true);
        bWriter = new BufferedWriter(fWriter);

        //Convert Result objects to JSON and write to file
        for(int j = 0; j < strings.length; ++j) {
            bWriter.write(strings[j]);
                bWriter.newLine();
                System.out.println("done");
        }
    }
    catch(IOException e) {e.printStackTrace();}

在这之前,我有几乎相同的代码2到3次, BufferedWriter 正在写入完美。但由于某种原因,当我到这个代码它不写。我一直在寻找可能是错误的东西,但我不能改变一些东西,并快速测试,因为程序需要10分钟才能到达这部分。

I have pretty much the same code 2 or 3 times before this and BufferedWriter is writing perfectly. But for some reason when I get to this code it doesn't write. I've been looking for things that might be wrong but I can't change something and test it quickly as the program takes 10 minutes just to get to this part.

另外,程序在控制台输出done,所以我知道它是进入 for循环

Also, the program prints "done" to the console so I know it is going into the for loop.

任何想法,我在做什么错了?

Any ideas as to what I'm doing wrong?

推荐答案

调用 bWriter.flush() code>当你想要你的数据实际上被刷新到你的文件在磁盘上。
或者当您完成作者的工作时,只需调用 bWriter.close()即可。
bWriter.close()
调用将在内部调用 bWriter.flush()

Call bWriter.flush() when you want your data to actually be flushed to your file on disk. Or just call bWriter.close() when you're done working with your writer. The bWriter.close() call will call bWriter.flush() internally.

这篇关于为什么BufferedWriter不写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆