Java 在txt文件上写入文本及其方法

Java 在txt文件上写入文本及其方法,java,arraylist,text,filewriter,Java,Arraylist,Text,Filewriter,所以我现在正在做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++) {

所以我现在正在做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();
    }
public void save(字符串文件、列表文本)引发IOException{
FileWriter f=新的FileWriter(文件,true);
对于(int i=0;i
但不是这个代码:

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();
    }
public void save(字符串文件、列表文本)引发IOException{
FileWriter f=新的FileWriter(文件,true);
用于(字符串文本:文本){
f、 写(文本);
System.out.println(“”);
}
f、 close();
}

尝试在第二个代码中写一个行分隔符,如下所示:

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

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

System.out.println(“”)不写入文件,而是写入控制台。您的文件不会有新行字符。因为第一个代码段将换行符写入文件,第二个代码段将换行符写入
System.out
而不是文件。问题是为什么您会假设第二个代码是有效的……好吧,如果我删除System.out.println(“”;,它会把所有的文字写在一行上,对吗?