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.
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?
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) ;
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.