Java - 检查 .txt 所有行中的现有文本

发布于 2024-11-15 22:53:51 字数 272 浏览 3 评论 0 原文

基本上,我希望根据某一行是否已经存在来添加到 .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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

假装爱人 2024-11-22 22:53:51

您可以按照您的建议使用 readLine() 方法rel="nofollow">RandomAccessFile 读取文件的每一行,查找预期的文本。

来自 readLine() 的 javadoc:

一行文本以
回车符 ('\r')、a
换行符 ('\n')、a
立即回车符
后跟换行符,或
文件末尾。

如果未找到所需的文本,则可以使用 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():

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.

枉心 2024-11-22 22:53:51

为什么不使用循环并逐行读取文本文件?循环结束后,如果找不到该行,请将其附加到文件末尾。

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.

梦亿 2024-11-22 22:53:51

您基本上首先必须扫描部分或全部,查找您要查找的单词,然后附加该单词​​(如果不存在)。

您可以使用 readLine(),但是如果您不介意第三方库,您可以尝试 番石榴

File theFile = ...
String theWord = ...

String text = Files.toString(theFile, "utf-8");
if (!text.contains(theWord)) {
   Files.append(theWord,  theFile, "utf-8")
}

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")
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文