Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Writing to a specific line in a file

Status
Not open for further replies.

saadabc

Programmer
Aug 5, 2004
107
US

Is it possible in Java to write to a specific line in a file.

I've been using the FileOutputStream object to write to files.... but i don't know how i can write to, say, the 20th line in a file using this.


Waseem
 
You could look into using a RandomAccessFile, and seek to the desired position in the file, and insert data.

Or you could read the file, writing each line to a new file until you hit the desired point of insert, write your new data, and then dump the rest of the file to your new file, and finally rename your file to your original one.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Im trying the same thing out at the moment.

with regards to the random access file how would i search for a specific line of text and insert after that line?
ive looked at the various methods that exist for the random access file but cant seem to figure out how exactly you would use them for searching in this manner.

would i have to read through the file as a normal file, find the string, take the location of where i want to insert the data and then insert the data into the random access file at that point?

or would this cause problems in differences between file pointers, byte positions etc or be just wholey inefficient.

would i be better off concatonating the file, adding the data to a temp file etc as you suggested?

thanks
 

Thanks.

I've ended up reading everything from the file into an array, adding the changes for the file into the array, and then writing everything from the array into the file. I make sure that when I write the first line, I'm overwriting the content of the file - and then appending the content in subsequent writes. so essentially do this:


FileOutputStream fout = new FileOutputStream(filename, false) ;
PrintStream pstr = new PrintStream(fout) ;

pstr.println(tempArray[0]) ;


then:


FileOutputStream fout = new FileOutputStream(filename, true) ;
PrintStream pstr = new PrintStream(fout) ;

// write rest of the content of the array



Thanks.




 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top