【问题标题】:writing text on a txt file and ways to do it在 txt 文件上写入文本及其方法
【发布时间】: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.outnot 写入文件。问题是为什么你会假设第二个代码是有效的......
  • 好的,如果我删除 System.out.println("");,它会将所有文本写在一行上,对吧?

标签: java arraylist text filewriter


【解决方案1】:

尝试在第二个代码中写一个行分隔符:

for (String text : texts) {
     f.write(text);
     f.write(System.lineSeparator());
}

如 cmets 中所述,System.out.println 改为写入控制台

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 2021-10-17
    • 2012-07-19
    相关资源
    最近更新 更多