如何写下一行到文件

时间:2017-07-23 23:11:50

标签: java io

我尝试过使用writer.newLine(),但是说找不到方法。有没有人知道如何在每次迭代后写一个新行?

 public static void keepLetters() throws IOException {
        BufferedReader sourceReader = new BufferedReader(new FileReader("input.txt"));

        for (String line = sourceReader.readLine(); line != null; line = sourceReader.readLine()) {
            String updatedLine = line.replaceAll("[^A-Za-z]", "");
            System.out.println(updatedLine);

            try (Writer writer = new BufferedWriter(new OutputStreamWriter(
                                 new FileOutputStream("output.txt"), "UTF-8"))) {
                    writer.write(updatedLine);
            }
        }

    }

我在writer.nextLine()之后写了writer.write(updatedLine);

谢谢

2 个答案:

答案 0 :(得分:3)

正确的方法是newLine(),但您需要在BufferedWriter上调用,而不是Writer

像这样:

try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                                 new FileOutputStream("output.txt", true), "UTF-8"))) {
                                 writer.write(updatedLine);
                                 writer.newLine();
            }

请注意此部分try (BufferedWriter writer

更新评论

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8"));

for (int i = 0; i < linesToWrite; i++){
    writer.write(updatedLine);
    writer.newLine();
}
writer.close();

答案 1 :(得分:0)

你可以简单地做到

writer.write(updatedLine + "\n");

将确保在每个updatedLine之后写入换行符。

编辑:

在循环的每次迭代中,编写器都重新启动到相同的文件输出。它应该在循环之前初始化一次,稍后关闭以解决您的问题。