Search code examples
javafilefile-iooverwriteread-write

Read and Writing to a file simultaneously in java


I'm reading a file line by line, and I am trying to make it so that if I get to a line that fits my specific parameters (in my case if it begins with a certain word), that I can overwrite that line.

My current code:

try {
    FileInputStream fis = new FileInputStream(myFile);
    DataInputStream in = new DataInputStream(fis);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String line;

    while ((line = br.readLine()) != null) {
        System.out.println(line);
            if (line.startsWith("word")) {
                // replace line code here
            }
    }
} catch (Exception ex) {
    ex.printStackTrace();
}

...where myFile is a File object.

As always, any help, examples, or suggestions are much appreciated.

Thanks!


Solution

  • Your best bet here is likely going to be reading in the file into memory (Something like a StringBuilder) and writing what you want your output file to look like into the StringBuilder. After you're done reading in the file completely, you'll then want to write the contents of the StringBuilder to the file.

    If the file is too large to accomplish this in memory you can always read in the contents of the file line by line and write them to a temporary file instead of a StringBuilder. After that is done you can delete the old file and move the temporary one in its place.