【发布时间】:2020-03-11 08:41:21
【问题描述】:
所以我现在正在做 MOOC 练习,它要求我使用 ArrayList 在 txt 文件上写一个文本。 我只是不明白为什么它接受了这个代码:
public void save(String file, List<String> texts) throws IOException {
FileWriter f = new FileWriter(file, true);
for (int i = 0; i < texts.size(); i++) {
f.write(texts.get(i) + "\n");
}
f.close();
}
但不是这段代码:
public void save(String file, List<String> texts) throws IOException {
FileWriter f = new FileWriter(file, true);
for (String text : texts) {
f.write(text);
System.out.println("");
}
f.close();
}
【问题讨论】:
-
System.out.println("");不会写入文件,而是写入控制台。您的文件不会有换行符。 -
因为第一个 sn-ps 将换行符写入文件,第二个将换行符写入
System.out而 not 写入文件。问题是为什么你会假设第二个代码是有效的...... -
好的,如果我删除 System.out.println("");,它会将所有文本写在一行上,对吧?
标签: java arraylist text filewriter