Reading and writing to a file at the same time in java

I am reading the file line by line, and I am trying to make sure that if I get to the line that matches my specific parameters (in my case, if it starts with a specific word), I can overwrite this line.

My current code is:

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 greatly appreciated.

Thanks!

+7
source share
2 answers

Your best bet here will most likely be to read the file into memory (something like StringBuilder ) and write what you want your output file to look like StringBuilder . After you finish reading the file completely, you will want to write the contents of the StringBuilder file to the file.

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

+4
source

RandomAccessFile seems good. His javadoc says:

Instances of this class support reading and writing to a random access file. A random access file behaves like a large array of bytes stored in the file system. There is some kind of cursor or index in an implied array called a file pointer; input operations read bytes from the file pointer and advance the file pointer bytes read. If a random access file is created in read / write mode, output operations are also available; output operations write bytes, starting with the file pointer, and advance the file pointer beyond the written bytes. The output operations that are written to the current end of the implied array cause the array to expand. The file pointer can be read by the getFilePointer method and set by the search method.

However, since text files are a sequential file format, you cannot replace a string with a line of different lengths without moving all subsequent characters around, so replacing strings in the general case will be to read and write the entire file. It may be easier to do if you write to a separate file and rename the output file as soon as you are done. It is also more stable if something goes wrong, as you can simply repeat with the contents of the source file. The only advantage of RandomAccessFile is that you do not need disk space for a temporary output file and can get a little improved disk performance due to better availability.

+12
source

All Articles