我一直在致力于从多个.txt文件中读取数据以将其转换为.csv文件的项目。我的问题是,导出的数据不断覆盖第一行,因此每次我导出文件时,它仅显示最后一行。有人有任何提示可以帮助我吗?
//Reading the information from the files.
for (String fileName : textFileNames) {
try (Scanner sc = new Scanner(new File(stack + "\\" + fileName));) {
fileIn = sc.nextLine();
while (fileIn != null) {
String line = fileIn;
String[] split = line.split("\\s+");
StringJoiner joiner = new StringJoiner(",");
for (String strVal : split) {
joiner.add(strVal);
}
line = joiner.toString();
line = line.startsWith(",") ? line.substring(1) : line;
System.out.println(line);
BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv"));
StringBuilder sb = new StringBuilder();
// Append strings from array
sb.append(line);
sb.append("\n");
br.write(sb.toString());
br.close();
fileIn = sc.nextLine();
}
sc.close();
} catch (IOException ex) {
Logger.getLogger(Class_Organizer_Krause.class.getName())
.log(Level.SEVERE, null, ex);
}
}
答案 0 :(得分:1)
您正在while循环中重新创建BufferedWriter
,实际上是每次您循环到输入文件中的新行时都重新创建文件。
将BufferedWriter的构造移出while循环(在其之前),将close语句移至while循环之后,这应该没问题。
答案 1 :(得分:1)
BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv", true));
应该可以解决您的问题。
通过这种方式,您应该将这些创建的资源移至try
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html内,以免发生异常时拥有未封闭的资源
try (Scanner sc = new Scanner(new File(stack + "\\" + fileName));
FileWriter fw = new FileWriter("myfile.csv", true);
BufferedWriter br = new BufferedWriter(fw);
) {
...
// you can remove br.close();
}