如何将结果保存到Excel文件或csv文件?

用户名

我正在使用以下代码提取一些数据并将其保存到CSV文件。但是现在的问题是该程序将数据写入CSV文件,并且每当代码再次运行时,该数据就会被删除,而旧结果将被新结果替换!问题是,是否可以保存结果并将新结果存储在新行中?如果是,那该怎么办?

这是我的代码:

 private void writeReport() {
    BufferedWriter out = null;
   try {
        FileWriter fstream = new FileWriter("out.csv");
        out = new BufferedWriter(fstream);
        out.write("File Name;");
        out.write("Total Lines of Code;");
        out.write("Executable Lines;");
        out.write("Lines of Comments;");
        out.write("Trivial Lines;");
        out.write("Empty Lines;");
        out.write("Code Complexity;");
        out.write("Number of Files;"); //to be changed to numver of files 
        out.write("Average File Complexity;"); //to be changed to averag file complexity
        out.write("Comment Percentage;"); //total
        out.write("Total Lines of Test Code;");
        out.write("Total Comments in Tests;");
        out.write("Total Trivial Lines in Tests;");
        out.write("Total Empty Lines in Tests;");
        out.write("Total Number of Test Files;");
        out.write("Comment Presentage in Test;");

        out.write(System.getProperty("line.separator"));

      //  for (int i = 0; i < newFiles.getNrOfFiles(); i++) {
            out.write("test" + ";");
        //    out.write(newFiles.getParser(i).getSourceFile().getName()+ ";");
            out.write(String.valueOf(newFiles.sumLinesOfCode()) + ";");
            out.write(String.valueOf(newFiles.sumLinesOfStatements()) + ";");
            out.write(String.valueOf(newFiles.sumLinesOfComments()) + ";");
            out.write(String.valueOf(newFiles.sumTrivialLines()) + ";");
            out.write(String.valueOf(newFiles.sumEmptyLines()) + ";");
            out.write(String.valueOf(newFiles.sumComplexity())+ ";");
            out.write(String.valueOf(newFiles.getNrOfFiles()) + ";");
            out.write(String.valueOf(newFiles.sumAvgComplexity()) + ";");
            out.write(String.valueOf((100 * newFiles.sumLinesOfComments()) / newFiles.sumLinesOfCode() + "%") + ";");

            out.write(System.getProperty("line.separator"));

        //Close the output stream
        out.close();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
      //  return;
    }
}
韦罗

确定文件是否已经存在

File file = new File("out.csv");
boolean exists = file.exists();

如果文件存在,然后以追加模式打开编写器

FileWriter fstream = new FileWriter(file, exists /*=append*/);

并仅在文件尚不存在时才写标头。

if (!exists) {
    out.write("File Name;");
    ...
    out.write(System.getProperty("line.separator"));
}
// write new rows

当您使用时,某些事情也会变得更容易PrintWriter

PrintWriter out;
...
PrintWriter out = new PrintWriter(new BufferedWriter(fstream));
...
out.println(); // easier than out.write(System.getProperty("line.separator"));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章