【发布时间】:2012-01-11 14:43:17
【问题描述】:
假设我有一个字符串 =“你好”。如何打开一个文本文件并检查该文本文件中是否存在 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.");
}
【问题讨论】:
-
String myArray[] = str.split(":");java String 类中有很多方法可以处理这类事情。 -
您的文件只包含一行...所以 readline 在读取该行时退出循环,因为第二次 in.readline 返回 null
-
您对
BufferedReader的使用似乎是正确的。你没有看到“hello.txt”的逐行输出吗? -
我的文本文件不止一行,我这里只显示一行。有没有更好的方法来检查一个字符串“hello”是否在文本文件中?