java 使用java在文本文件中查找单词的行号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7548519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding line number of a word in a text file using java
提问by Neel
I require searching a word in a text file and display the line number using java. If it appears more than once I need to show all the line numbers in the output. Can anyone help me please?
我需要在文本文件中搜索一个单词并使用 java 显示行号。如果它出现不止一次,我需要在输出中显示所有行号。有人可以帮我吗?
回答by Simon C
Read the text file using Java class LineNumberReader
and call method getLineNumber
to find the current line number.
使用 Java 类LineNumberReader
和调用方法读取文本文件getLineNumber
以查找当前行号。
http://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html
http://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html
回答by Johan Sj?berg
You can store this information manually. Whenever you are invoking readline()
of your BufferedReader
, if you're using such, you can also increment a counter by one. E.g.,
您可以手动存储此信息。每当您调用readline()
您的 时BufferedReader
,如果您正在使用它,您还可以将计数器加一。例如,
public int grepLineNumber(String file, String word) throws Exception {
BufferedReader buf = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(file))));
String line;
int lineNumber = 0;
while ((line = buf.readLine()) != null) {
lineNumber++;
if (word.equals(line)) {
return lineNumber;
}
}
return -1;
}
回答by Ted Hopp
Something like this might work:
像这样的事情可能会奏效:
public ArrayList<Integer> find(String word, File text) throws IOException {
LineNumberReader rdr = new LineNumberReader(new FileReader(text));
ArrayList<Integer> results = new ArrayList<Integer>();
try {
String line = rdr.readLine();
if (line.indexOf(word) >= 0) {
results.add(rdr.getLineNumber());
}
} finally {
rdr.close();
}
return results;
}