我当前的代码仅读取文件的最后一行。有人可以帮我建立一种方法,使代码逐行读取文件吗?
import java.util.*;
import java.io.*;
public class Searcher extends File {
Scanner scn;
public Searcher(String filename) {
super(filename);
}
public void search(String input)
{
try {
scn = new Scanner(this);
String data = "";
while (scn.hasNext()) {
data = scn.nextLine();
}
int count = 0, fromIndex = 0;
while ((fromIndex = data.indexOf(input, fromIndex)) != -1) {
count++;
fromIndex++;
}
System.out.println("Total occurrences: " + count);
scn.close();
} catch (Exception e) {
System.out.println("Cant find file ");
}
}
public static void main(String[] args) {
Searcher search = new Searcher("src/ihaveadream.txt");
search.search("we");
}
}
感谢任何帮助!
答案 0 :(得分:3)
07-05 16:35:49.156 W/ActivityManager( 1167): Unable to start service Intent { act=com.google.android.c2dm.intent.UNREGISTER pkg=com.google.android.gsf (has extras) } U=0: not found
07-05 16:35:49.169 W/ActivityManager( 1167): Unable to start service Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gsf (has extras) } U=0: not found
您每次都会替换该值,因此最终会得到最后一个值,因为最后是该值。也许您想附加?
while (scn.hasNext()) {
data = scn.nextLine();
}
祝你好运。
答案 1 :(得分:1)
您的问题:
while (scn.hasNext()) {
data = scn.nextLine(); // right here
}
下一行替换上一行。
根据需要,您可以: 将所有行都设为一个字符串
data = data + scn.nextLine();
// another syntax to do the same:
data += scn.nextLine();
或使用列表将每行保留为单独的元素:
List<String> dataList = new ArrayList<>();
while (scn.hasNext()) {
dataList.add(scn.nextLine());
}
答案 2 :(得分:0)
正如每个人都已经建议的那样,您将在while循环中替换数据变量中的数据,由于循环一直运行到到达文件末尾,因此只有最后一行存储在data变量中,并且对数据的任何进一步处理都只会使您从最后一行得到结果,因此您可以做的是这里其他人的建议,或者您可以尝试将其作为替代解决方案(在检查索引值后关闭while循环): / p>
public void search(String input)
{
int count = 0, fromIndex = 0; //moved outside so that we don't reset it to 0 with every iteration of the loop
try {
scn = new Scanner(this);
String data = "";
while (scn.hasNext()) {
data = scn.nextLine();
//} instead of here
//int count = 0, fromIndex = 0; move these variables outside of the loop
while ((fromIndex = data.indexOf(input, fromIndex)) != -1) {
count++;
fromIndex++;
}
} //close it here
System.out.println("Total occurrences: " + count);
scn.close();
} catch (Exception e) {
System.out.println("Cant find file ");
}
}