3 回答
TA贡献1784条经验 获得超9个赞
有一个计数器并对每一行进行计数。
long count = 0;
long lineNumberCounter = 0;
List<Long> lineNumbers = new ArrayList<>();
try (BufferedReader b = new BufferedReader(new java.io.FileReader(new File(fileName)))) {
String readLine = "";
System.out.println("Reading file using Buffered Reader");
while ((readLine = b.readLine()) != null) {
// Here is line number counter
lineNumberCounter++;
String[] words = readLine.split(" "); // Split the word using space
System.out.println(Arrays.toString(words));
for (String word : words) {
// Search for the given word
if (word.trim().equals(input)) {
count++; // If Present increase the count by one
System.out.println("Word " + input + " found in line " + lineNumberCounter);
lineNumbers.add(lineNumberCounter);
}
}
}
}
// Check for count not equal to zero
if (count != 0) {
System.out.println("The given word is present for " + count + " Times in the file");
} else {
System.out.println("The given word is not present in the file");
}
TA贡献1843条经验 获得超7个赞
我认为这会有所帮助。
您所要做的就是跟踪行号,然后保存该单词可用的行
File f1=new File("input.txt")
String[] words=null; //Intialize the word Array
FileReader fr = new FileReader(f1); //Creation of File Reader object
BufferedReader br = new BufferedReader(fr);
String s;
String input="Java"; // Input word to be searched
int count=0; //Intialize the word to zero
// for keeping track of the line numbers
int lineNumber= 0;
//arraylist to save the numbers
List<int> lineNumberList = new ArrayList<>();
while((s=br.readLine())!=null) //Reading Content from the file
{
// increase the line number as we move on to the next line
lineNumber++;
words=s.split(" "); //Split the word using space
// this is required so that same line number won't be repeated on the arraylist
boolean flag = true;
for (String word : words)
{
if (word.equals(input)) //Search for the given word
{
count++; //If Present increase the count by one
if(flag){
lineNumberList.add(lineNumber);
flag=false;
}
}
}
}
if(count!=0) //Check for count not equal to zero
{
System.out.println("The given word is present for "+count+ " Times in the file");
}
else
{
System.out.println("The given word is not present in the file");
}
fr.close();
}
}
TA贡献1788条经验 获得超4个赞
尝试使用LineNumberReader而不是BufferedReader. 它支持 BufferedReader 和 LineNumber。
Javadoc 了解更多信息 - https://docs.oracle.com/javase/8/docs/api/java/io/LineNumberReader.html。
例子 -
LineNumberReader lineNumberReader =
new LineNumberReader(new FileReader("c:\\data\\input.txt"));
int data = lineNumberReader.read();
while(data != -1){
char dataChar = (char) data;
data = lineNumberReader.read();
// your word processing happens here
int lineNumber = lineNumberReader.getLineNumber();
}
lineNumberReader.close();
http://tutorials.jenkov.com/java-io/linenumberreader.html
添加回答
举报