【发布时间】:2017-05-04 13:17:35
【问题描述】:
我有以下代码:
public static void main(String[] args) throws IOException {
//File being read:
String fileName = "src/data/Belgium.csv";
String[] nextLine;
try (CSVReader reader = new CSVReader(new FileReader(fileName), ',', '"', 1)) {
while ((nextLine = reader.readNext()) != null) {
for (String line : nextLine) {
//NewFile
//When 2nd parameter - ture, it gets so big, that excel can't handle it anymore...
FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", true);
line = line.replaceAll("T", " ");
line = line.replaceAll("Z", "");
line = line.replaceAll("ActualGenerationPerUnit.mean", "");
line = line.replaceAll("Plantname:", "");
//Escaping curly braces is a must!
line = line.replaceAll("\\{", "");
line = line.replaceAll("\\}", "");
writer.append(line);
writer.flush();
writer.close();
System.out.println(line);
}
}System.out.println("Successfully written");
}
}
我的控制台中的代码输出,使用 System.out.println(line) 给了我正确的输出。 但是,当我打开 CSV 文件时,它似乎被颠倒了。 Excel 首先抱怨行数。 但是,只有我的原始数据集的最后一行显示。 数据集(以低效的方式进行预处理)包含超过 1000 行。因此,我不能简单地附加每个条目。
有更好的方法吗?
非常欢迎提示和技巧。 此外,我尝试了几个作家: - CSV写入 - 缓冲作家 - 文件编写器
还检查了 Stackoverflow 上的其他问题... 似乎无法让它工作。谢谢!
更新:
问题已回答!最终代码:
public static void main(String[] args) throws IOException {
//File being read:
String fileName = "src/data/Belgium.csv";
//When 2nd parameter - ture, it gets so big, that excel can't handle it anymore...
FileWriter writer = new FileWriter("src/dataNew/BelgiumNew5.csv", true);
String[] nextLine;
try (CSVReader reader = new CSVReader(new FileReader(fileName), ',', '"', 1)) {
while ((nextLine = reader.readNext()) != null) {
for (String line : nextLine) {
line = line.replaceAll("T", " ");
line = line.replaceAll("Z", "");
line = line.replaceAll("ActualGenerationPerUnit.mean", "");
line = line.replaceAll("Plantname:", "");
//Escaping curly braces is a must!
line = line.replaceAll("\\{", "");
line = line.replaceAll("\\}", "");
writer.append(line);
writer.append(System.lineSeparator());
System.out.println(line);
}
}System.out.println("Successfully written");
}catch(Exception e){
e.printStackTrace();
}finally {
if (writer != null){
writer.flush();
writer.close();
}
}
}
【问题讨论】:
标签: java csv filewriter writer