Java - checking .txt for existing text across all lines
Basically, I am looking to add to a .txt file depending on whether a certain line exist already or not.
I.e. add the line to the .txt file if it doesn't exist already. Don't add the line to the .txt file if it exists.
Every line stands alone
E.g.
One
Two
Three
and not One, Two, Three etc.
I was thinking of using readLine() but it seems that it defines the end of a line when there's a break, like there my 开发者_C百科lines have. The method doesn't take any arguments (e.g. line numbers) so I'm pretty short-handen :/.
Any he
You can use, as you suggest, the readLine() method of RandomAccessFile to read each line of the file, looking for the expected text.
From the javadoc for readLine():
A line of text is terminated by a carriage-return character ('\r'), a newline character ('\n'), a carriage-return character immediately followed by a newline character, or the end of the file.
If the expected text is not found, then you can use one of the write methods of RandomAccessFile, e.g. writeUTF() or writeBytes() to add the line of text to the file.
Why don't you use a loop and read the text file line by line? After the loop, if you didn't find the line, append it to the end of the file.
You basically first have to scan parts of or the whole, file for the word you are looking for and then append the word if it doesn't exist.
You could use readLine()
, however if you don't mind a third party lib you might try Guava:
File theFile = ...
String theWord = ...
String text = Files.toString(theFile, "utf-8");
if (!text.contains(theWord)) {
Files.append(theWord, theFile, "utf-8")
}
精彩评论