【问题标题】:BufferedWriter won't write all of the data to a file [duplicate]BufferedWriter 不会将所有数据写入文件[重复]
【发布时间】:2012-07-25 23:18:31
【问题描述】:

所以我写了一个程序,假设将两个LinkedList的内容以格式写入文本文件

"标题行 1"

"标题第 2 行"

“标题第 3 行”

x1 y1

x2 y2

x3 y3

...

x1023 y1023

主要编写代码如下:

    LinkedList<Double> xVal;
    LinkedList<Double> yVal;
    LinkedList<String> header;
    Analize test;
    Scanner scan = new Scanner(System.in);
    FileWriter fstream;
    BufferedWriter out;

    int i=1;
    test = new Analize(i);
    test.addData();
    test.calculate();


    //Writing ModY
    fstream = new FileWriter("BLOCK " +i+"_ModY.txt");
    out = new BufferedWriter(fstream);
    header = test.getHeader();
    xVal=test.getXList();
    yVal=test.getYListMod();


    //Write Header
    out.write(header.get(0)+"_modY");out.newLine();
    out.write(header.get(1));out.newLine();
    out.write(header.get(2));out.newLine();

    for(int j=0;j<xVal.size();j++)
    {
        double x=xVal.get(j);
        double y=yVal.get(j);
        out.write(x+"\t"+y+" "+j);out.newLine();
        //test code
        System.out.println(xVal.get(j)+"    "+yVal.get(j)+" "+j);
        //System.out.println(j);
    }

真正烦人的是测试代码行: System.out.println(xVal.get(j)+" "+yVal.get(j)+" "+j); 实际上在 System.in 中使用正确的值运行了 1023 次,但该文件的值只有第 558 次。

我不太确定这里发生了什么......

【问题讨论】:

  • 您是否刷新并关闭了编写器和/或流?

标签: java file bufferedwriter


【解决方案1】:

我没有看到你在任何地方打电话给out.close();。这将为您刷新并关闭底层流。我会把它放在你的 for 循环之后。

始终确保关闭您的流,否则您的一些数据可能会在内存中等待 JVM 出现并将其刷新到您的文件中。

【讨论】:

  • 非常感谢!我确实在代码的其他部分这样做了。我不敢相信在大约 3 小时的故障排除后我没有看到这个。
【解决方案2】:

除了what Cory said,始终在 finally 块中关闭底层流,以确保无论出现异常情况它们都会关闭。

【讨论】:

  • 当你在适当的时候关闭缓冲流时,它不会为你关闭底层流吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-18
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-27
相关资源
最近更新 更多