简体   繁体   中英

Iterate the lines in the file and add null value at end of each line

I am trying to add a keyword null (to be more specific ,null ) at end of each line in a file. I tried the below mentioned code but no effect on the file. Note: TESTFILE is a existing file with 10 line and I have to append ,null at end of each line.

final String FILENAME = "D:\\TESTFILE"
FileWriter fileWriter = new FileWriter(FILENAME, true);
BufferedWriter bw =  new BufferedWriter(fileWriter);
FileReader fileReader = new FileReader(FILENAME);
BufferedReader br = new BufferedReader(fileReader);
PrintWriter printWriter =  new PrintWriter(bw);
String line;

while ((line = br.readLine()) != null) {
        printWriter.println(",null");
    }
}

The problem here is that you are trying to read and write to the same file in the same time, this won't work, you need to to do this separately.

  1. Read your file.
  2. Update each line content.
  3. Save the updated line to a new temporary file.
  4. Save this new temp file and remove your original file after reading all lines.
  5. And finally rename the temp file to your original file name.

You can check Modifying existing file content in Java for further details on how to implement it.

As stated in the other answer, make sure you read from one file and write to another. Which is always a good idea as you don't loose the original while making small mistakes. Of course you can also delete the backup file once finished, that is up to you.

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;

public class Modify {
    public void modify(Path file, String append) throws IOException {
        Path backup = file.resolveSibling(file.getFileName().toString() + "~");
        Files.move(file, backup, StandardCopyOption.REPLACE_EXISTING);

        try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file, StandardOpenOption.CREATE))) {
            Files.lines(backup)
                .map(l -> l.concat(append))
                .forEach(writer::println);
        }
    }

    public static void main(String... args) throws IOException { 
        new Modify().modify(Paths.get("/path/to/whatever"), ",null");
    }
}

But, honestly, adding ,null in a 10 line file, I'd do that manually by copying/pasting it.

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