在分隔文本文件中搜索字符串
假设我有一个字符串=“hello”。如何打开一个文本文件并检查该文本文件中是否存在 hello?
文本文件的内容:
hello:man:yeah
我尝试使用下面的代码。文件读取器只读取第一行吗?我需要它检查所有行以查看 hello 是否存在,然后如果存在,则从中取出“man”。
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
System.out.println("Error.");
}
Lets say I have a string = "hello". how do i open a text file and check if hello exists in that text file?
contents of the text file:
hello:man:yeah
i tried using the code below. Is it file reader only reads the first line? i need it to check all lines to see if hello exists, and then if it does, take "man" from it.
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
System.out.println("Error.");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果 hello:man:yeah 是文件中的一行,那么您的代码工作正常。 readLine() 将读取一行,直到找到换行符(在本例中为一行)。
如果您只想查看它是否在文件中,那么您可以执行以下操作:
如果您需要进行整个单词搜索,则需要使用正则表达式。用 \b 包围搜索文本将进行整个单词搜索。这是一个片段(注意,StringUtils 来自 Apache Commons Lang):
当然,如果你没有多个令牌,你可以这样做:
If hello:man:yeah is one line in your file, then your code is working right. readLine() will read a line until a newline is found (one line in this case).
If you just want to see if it's in the file, then you could do something like this:
If you need to do a whole word search, you'll need to use a regular expression. Surrounding your search text with \b will do the whole word search. Here's a snippet (Note, StringUtils comes from Apache Commons Lang):
Of course, if you don't have multiple tokens, you can just do this:
使用
String.indexOf()
或String.contains()
方法。Use
String.indexOf()
orString.contains()
method.在每一行上使用
String.contains
方法。每一行都在 while 循环中处理。Use the
String.contains
method on each line. Each line is processed in the while loop.