基本上,我希望根据某一行是否已经存在来添加到 .txt 文件。
即,如果 .txt 文件尚不存在,则将该行添加到该文件中。
如果 .txt 文件存在,请勿将该行添加到该文件中。
每行都是独立的,
例如
一
二三
而
不是
一、二、三等。
我正在考虑使用 readLine() 但它似乎在有中断时定义了行的结尾,就像我的行一样。该方法不接受任何参数(例如行号),所以我很缺手:/。
任何他
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 lines have. The method doesn't take any arguments (e.g. line numbers) so I'm pretty short-handen :/.
Any he
发布评论
评论(3)
您可以按照您的建议使用 readLine() 方法rel="nofollow">RandomAccessFile 读取文件的每一行,查找预期的文本。
来自 readLine() 的 javadoc:
如果未找到所需的文本,则可以使用 RandomAccessFile,例如 writeUTF() 或 writeBytes() 将文本行添加到文件中。
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():
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.
您基本上首先必须扫描部分或全部,查找您要查找的单词,然后附加该单词(如果不存在)。
您可以使用
readLine()
,但是如果您不介意第三方库,您可以尝试 番石榴: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: