简体   繁体   English

使用BufferedReader和FileWriter附加行

[英]Append Lines using BufferedReader and FileWriter

I'm trying to parse the code in a file and copy it to a newly created file with the relevant modifications. 我正在尝试解析文件中的代码,并通过相关修改将其复制到新创建的文件中。

However, in the new file all that appears is the final line from the original file. 但是,在新文件中,所有出现的都是原始文件的最后一行。

How do I ensure all the lines get copied to the new file, and not just the last one? 如何确保所有行都复制到新文件中,而不仅仅是最后一行?

Note: I want a new file to be created every time I run this program, so this question isn't about the FileWriter constructor with 'true' passed in as shown below 注意:我希望每次运行该程序时都可以创建一个新文件,因此此问题与FileWriter构造函数无关,传递了“ true”,如下所示

FileWriter fw = new FileWriter(newFile.txt, true);

Here is the relevant piece of code: 这是相关的代码段:

try (BufferedReader bufferedReader = new BufferedReader(new FileReader(args[0]));
        FileWriter fileWriter = new FileWriter(myNewFile.txt)) {

        while (bufferedReader.readLine() != null) {
            String currentLine = bufferedReader.readLine();
            fileWriter.write(currentLine);
        }

myNewFile.txt only contains the last line of text from the file passed in to the BufferedReader. myNewFile.txt仅包含传递到BufferedReader的文件的最后一行文本。 I don't know of any append functions provided by the FileWriter class. 我不知道FileWriter类提供的任何附加函数。

Thanks 谢谢

EDIT (SOLUTION): 编辑(解决方案):

The problem was resulting from the initialization of currentLine in the while loop. 该问题是由while循环中currentLine的初始化引起的。 I changed it to 我将其更改为

String currentLine;
while ((currentLine = bufferedReader.readLine()) != null) {
    fileWriter.write(currentLine);
}
new FileWriter(myNewFile.txt, true)

这将启用附加模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM