将新行添加到BufferedWriter

时间:2018-12-18 02:20:34

标签: java

如果通过writeMore()作为最后一个参数传递,则每次写入true的新行时,我都尝试写入文本文件。但是,作者继续写到同一第一行的末尾。我不明白问题是什么。

package FileIO;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Buffered_Writer {

    public static void main(String[] args) throws IOException{

        String fileName = "myFile.txt";
        String message = "I'm written into the file.";

        File myFile = new File("C:\\Users\\User\\Desktop\\" + fileName);
        try {
            myFile.createNewFile();
        } catch (Exception e) {
            System.out.println("Could not create file!");
        }


        BufferedWriter writer = new BufferedWriter(new FileWriter(myFile, true));
        writer.write(message);

        writeMore("This much more has been written.", myFile, true);

        writer.close();
    }

    public static void writeMore(String message, File file, boolean newLine) throws IOException{

        BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
        if (newLine) {
            writer.append(" \n");
            writer.append(message);
        }
        else {
            writer.append(" " + message);
        }
        writer.close();
    }
}

3 个答案:

答案 0 :(得分:2)

为什么不使用正确的方法

https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#newLine()

根据javadocs

  

编写一个行分隔符。行分隔符字符串由   系统属性line.separator,不一定是单个   换行符('\ n')。

答案 1 :(得分:0)

给予

File myFile = new File("C:\\Users\\User\\Desktop\\" + fileName);

我可以推断出您在Windows上。 Windows的行分隔符不是\n(它是\r\n,但不要对其进行硬编码)。请改用System.lineSeparator()。更改

writer.append(" \n");

writer.append(System.lineSeparator());

答案 2 :(得分:0)

最好的解决方案是使用BufferedWriter.newLine()方法。此外,BufferedWriter应该正确关闭(使用try with resources):

public static void writeMore(String message, File file, boolean newLine) throws IOException {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) {
        if (newLine) {
            writer.newLine();
            writer.append(message);
        } else
            writer.append(" ").append(message);
    }
}