简体   繁体   中英

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 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. I don't know of any append functions provided by the FileWriter class.

Thanks

EDIT (SOLUTION):

The problem was resulting from the initialization of currentLine in the while loop. I changed it to

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

这将启用附加模式

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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