I have a text file where I want to change only the first line of the file. The file could be millions of rows long, so I’d rather not have to loop over everything, so I’m wondering if there is another way to do this.
I’d also like to apply some rules to the first line so that I replace instances of certain words with other words.
Is this possible?
A
RandomAccessFilewill do the trick, unless the length of the resulting line is different from the length of the original line.If it turns out you are forced to perform a copy (where the first line is replaced and the rest of the data shall be copied as-is), I suggest using a
BufferedReaderandBufferedWriter. First useBufferedReader‘sreadLine()to read the first line. Modify it and write it to theBufferedWriter. Then use achar[]array to perform a brute-force copy of the remainder of the file. This will be more efficient than doing the copy line by line. Let me know if you need details..Another option is to perform the reading and writing inside the same file. It’ll be a bit more complex though. 🙂 Let me know if you need details on this as well..