![](/img/trans.png)
[英]Finding a word with the most consecutive vowels in a text file, using Java
[英]Finding line number of a word in a text file using java
我需要在文本文件中搜索單詞並使用java顯示行號。 如果它出現不止一次,我需要在輸出中顯示所有行號。 有人可以幫我嗎?
使用Java類LineNumberReader
讀取文本文件,並調用方法getLineNumber
以查找當前行號。
http://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html
您可以手動存儲此信息。 無論何時調用BufferedReader
readline()
,如果你正在使用它,你也可以將計數器遞增1。 例如,
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;
}
像這樣的東西可能會起作用:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.