The only way I have managed is to create a temp file to do this, but this is not what I want. Can someone provide an example of how to replace the Nth line of a text file with a string WITHOUT making a temp file.
Thanks in advance =)
The only way I have managed is to create a temp file to do this, but this is not what I want. Can someone provide an example of how to replace the Nth line of a text file with a string WITHOUT making a temp file.
Thanks in advance =)
You can use RandomAccessFile...this provides read and write to file at same time...so you dont need to create temp file...
Idea is to skip through N-1 th line using readLine..
then count bytes of seventh line and compare with your replaceString bytes...
if replaceStringBytes < seventhLineBytes then replace entire seventh line bytes and continue reading after seventh line and moving the bytes before in file...
if replaceStringBytes > seventhLineBytes then create buffer of difference in bytes and store additional bytes after seventh line... continue filling up the buffer with difference each time you move forward...
here is a thread which will give you some hint...
Java - delete line from text file by overwriting while reading it