【问题标题】:FileWriter output to csv file is blankFileWriter 输出到 csv 文件为空白
【发布时间】:2017-09-22 06:42:00
【问题描述】:
FileWriter outfile = new FileWriter("ouput.csv", true); //true = append

        for(int len = 0; len < tempList.size(); len++) {
            LineItem tempItem = tempList.get(len);
            if ( len == 0 ) {
                lastTime = tempItem.getTimeEnd();
                tempItem.setStatus("OK");
                //out
                output( tempItem.toCSV(), outfile);
            } else {
                if ( tempItem.getTimeStart().compareTo(lastTime) <= 0 ) {
                    //WARN
                    if (!tempItem.getStatus().equals("OVERLAP")) {
                        tempItem.setStatus("WARN");
                    }

                } else {
                    //OK
                    //System.out.println( "OK  ;" + tempItem.toCSV());
                    if (!tempItem.getStatus().equals("OVERLAP")) {
                        tempItem.setStatus("OK");
                    }
                }
                // file out write
                output( tempItem.toCSV(), outfile);

                lastTime = tempItem.getTimeEnd();

            }

        }
    }

    private static void output(String line, FileWriter outfile) throws IOException {
        System.out.println(line);

        // Write each line to a new csv file
        outfile.write(line + "\n");

    }

为什么我的 output.csv 文件为 0 kb 且为空​​?但是当我打印到行时,我会在控制台中看到每个字符串...

【问题讨论】:

  • 考虑在FileWriter 上调用flush()close()

标签: java csv filewriter file-writing


【解决方案1】:

您没有关闭FileWriter

NB 刷新和关闭的建议是多余的。

【讨论】:

    【解决方案2】:

    output( tempItem.toCSV(), outfile); 之后请添加以下语句。你忘了flushClose 自动为你flush

    outfile.close();
    

    【讨论】:

      【解决方案3】:

      当您flush(outfile) 时,它将被写入文件。

      当您close(outfile) 时,它也会自动刷新。有时您想在其他时间flush(),但通常没有必要。您应该始终在完成文件后关闭它们。

      从 Java 7 开始,使用 try-with-resources 通常是个好主意:

      try(FileWriter outfile = new FileWriter("output.csv", true)) {
          // code that writes to outfile
      }
      

      因为FileWriter实现了Closeable,所以当执行离开这个块时,它会自动调用outfile.close()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-12
        相关资源
        最近更新 更多