I need to search a file for a word and return the whole line and the line number with this word, then edit the line and write back to the file. Maybe the line number isn’t necesary to edit a line in a file. I `was reading after seraching with regexp and opening the filechannel of the file, but I can’t get the line number. Maybe there are other better ways to do this. Can you help me how to start this?
Share
First to avoid a potential misconception, you can’t edit a file on the fly by just pointing out the line number and changing the line. You would need to read the whole content and write the whole content back to the same file at any way, even though you only need to edit a single character.
As to the line numbers, you can just add an incremental counter to the loop wherein you read each line of the file using
BufferedReader#readLine(). You can also use theLineNumberReader, but this doesn’t really work as starters would expect. So does for instancesetLineNumber()actually not skip the lines to the given line.