作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在使用以下代码提取一些数据并将它们保存到 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"));
关于java - 如何将结果保存到 Excel 文件或 csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36630895/
我是一名优秀的程序员,十分优秀!