Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is for Java I'm trying to write a program that writes to a text file using PrintWriter. I've been able to add text to the end of the file but I need to be able to write text in between two words.

Ex: 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 String from there.

What would be the best way to go about this?

like image 216
Nicholas Doubrovsky Avatar asked Apr 11 '26 02:04

Nicholas Doubrovsky


1 Answers

You could use a RandomAccessFile class.

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

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

Moving Around a RandomAccessFile

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

Here is a simple example:

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

file.seek(200);

long pointer = file.getFilePointer();

file.close();

Reading from a RandomAccessFile

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

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

int aByte = file.read();

file.close();

The read() method reads the byte located a the position in the file currently pointed to by the file pointer in the RandomAccessFile instance.

Here is a thing the JavaDoc forgets to mention: The read() method increments the file pointer to point to the next byte in the file after the byte just read! This means that you can continue to call read() without having to manually move the file pointer.

Writing to a RandomAccessFile

Writing to a RandomAccessFile can be done using one it its many write() methods. Here is a simple example:

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

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

file.close();

Just like with the read() method the write() method advances the file pointer after being called. That way you don't have to constantly move the file pointer to write data to a new location in the file.

close()

The RandomAccessFile has a close() method which must be called when you are done using the RandomAccessFile instance. You can see example of calls to close() in the examples above.

like image 52
Typo Avatar answered Apr 13 '26 15:04

Typo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!