How to write text between two lines in a text file. Java

This is for Java I am trying to write a program that writes to a text file using PrintWriter. I was able to add text to the end of the file, but I need to write text between two words.

Example: text before: dog mouse text after: dog cat mouse

The text file is relatively long, so I can't just read the whole thing and edit the line.

What would be the best way to do this?

+3


source to share


1 answer


You can use the RandomAccessFile class.

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

      

Notice the second input parameter to the constructor: "rw". This is the mode in which you want to open the file. "Rw" stands for read / write mode. Check the JavaDoc for more details on what modes you can open in RandomAccessFile.

Moving around RandomAccessFile

To read or write at a specific location in the RandomAccessFile, you must first place the file pointer in the read or write location. This is done using the seek () method. The current position of the file pointer can be obtained by calling the getFilePointer () method.

Here's a simple example:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

file.seek(200);

long pointer = file.getFilePointer();

file.close();

      

Reading from RandomAccessFile

Reading from RandomAccessFile is done using one of its many read () methods. Here's a simple example:



RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

int aByte = file.read();

file.close();

      

The read () method reads the byte where the file position is pointed to by the file pointer in the RandomAccessFile instance.

Here's what the JavaDoc says: The read () method increments the file pointer, pointing to the next byte in the file after the byte just read! This means that you can continue calling read () without having to manually move the file pointer.

Writing to RandomAccessFile

Writing to RandomAccessFile can be done using several write () methods. Here's a simple example:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

file.write("Hello World".getBytes());

file.close();

      

As with the read () method, the write () method advances the file pointer after the call. This way, you don't have to constantly move the file pointer to write data to a new location in the file.

close()

RandomAccessFile has a close () method that should be called when you're done using the RandomAccessFile instance. You can see an example of calls to close () in the examples above.

+1


source







All Articles