我正在使用 java 中的缓冲写入器编写一个 csv 文件。我的数据写入正确,但我希望数据所在的列有不同的列,目前它将每个日期实例写入一行,但不以列分隔。
代码是
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss");
File file = new File( dirName + "\\"+ df.format(new Date()) +"_Statistics.csv");
if ( !file.exists() )
file.createNewFile();
FileWriter fw = new FileWriter(file);
writer = new BufferedWriter( fw );
writer.write("Message Source");
writer.write("Message Name");
writer.write("Component");
writer.write("Occurance");
writer.write("Message Payload");
writer.write("Bandwidth (Payload)");
writer.write("Message Payload with Header");
writer.write("Bandwidth (Payload with Header)");
writer.newLine();
for (Signal signal : messages) {
writer.write(signal.getSource());
writer.write(signal.getName());
writer.write(signal.getComponent());
writer.write(Integer.toString(signal.getOccurance()));
writer.write(Integer.toString(signal.getSize()));
writer.write(Float.toString(signal.getBandwidth()));
writer.write(Integer.toString(signal.getSizewithHeader()));
writer.write(Float.toString(signal.getBandwidthWithHeader()));
writer.newLine();
}
writer.flush();
writer.close();
fw.close();
有什么方法可以明智地分离数据列以便正确读取?
编辑
我没有使用缓冲编写器,而是使用CSVReader
java 库。http://www.csvreader.com/java_csv.php
现在的代码是
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss");
File file = new File( dirName + "\\"+ df.format(new Date()) +"_Statistics.csv");
if ( !file.exists() )
file.createNewFile();
// Use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(file, true), ',');
//Create Header for CSV
csvOutput.write("Message Source");
csvOutput.write("Message Name");
csvOutput.write("Component");
csvOutput.write("Occurance");
csvOutput.write("Message Payload");
csvOutput.write("Bandwidth (Payload)");
csvOutput.write("Message Payload with Header");
csvOutput.write("Bandwidth (Payload with Header)");
csvOutput.endRecord();
for (Signal signal : messages) {
csvOutput.write(signal.getSource());
csvOutput.write(signal.getName());
csvOutput.write(signal.getComponent());
csvOutput.write(Integer.toString(signal.getOccurance()));
csvOutput.write(Integer.toString(signal.getSize()));
csvOutput.write(Float.toString(signal.getBandwidth()));
csvOutput.write(Integer.toString(signal.getSizewithHeader()));
csvOutput.write(Float.toString(signal.getBandwidthWithHeader()));
csvOutput.endRecord();
}
csvOutput.flush();
csvOutput.close();
它正确格式化了数据,但现在的问题是,当我第二次运行代码时,创建了第二个文件并且新文件包含重复的行,对于第一个文件中的每一行,第二个文件中有 2 行具有相似的数据。
是我没有清理一些资源吗?
谢谢