Finding line number of a word in a text file using java
I require searching a word in a text file and displ开发者_JS百科ay 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?
Read the text file using Java class LineNumberReader
and call method getLineNumber
to find the current line number.
http://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html
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;
}
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.,
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;
}
精彩评论