Hi All, I want to search this word "(Error: 87)" in my text file using Java code
Hi All, I want to search this word "(Error: 87)" in my text file using Java code
我试图在我的文本文件中搜索这个完整的词“(错误:87)”。
我使用了下面的 java 代码。
String path = "C:\Temp\Error_Hunter";
String fileName = "\nvr-service.txt";
String testWord = "(Error: 87)";
int tLen = testWord.length();
int wordCntr = 0;
String file1 = path + fileName;
boolean check;
try{
FileInputStream fstream = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while((strLine = br.readLine()) != null){
//check to see whether testWord occurs at least once in the line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if(check){
//get the line, and parse its words into a String array
String[] lineWords = strLine.split("\s+");
for(String w : lineWords)
{
if(w.length() >= tLen){
String word = w.substring(0,tLen).trim();
if(word.equalsIgnoreCase(testWord))
{
wordCntr++;
}
}
}
}
}
System.out.println("total is: " + wordCntr);
//Close the input stream
br.close();
} catch(Exception e){
e.printStackTrace();
}
在我的文本文件中,这个词有 104 次命中。但这不是找到这个词。因为它包含 space 之间。请提出一些建议或在代码本身中进行编辑。
而不是
String[] lineWords = strLine.split("\s+");
做
String[] tokens = strLine.split("(Error: 87)");
然后 (Error: 87)
在该行中出现的次数将是 tokens.length - 1
。
我试图在我的文本文件中搜索这个完整的词“(错误:87)”。 我使用了下面的 java 代码。
String path = "C:\Temp\Error_Hunter";
String fileName = "\nvr-service.txt";
String testWord = "(Error: 87)";
int tLen = testWord.length();
int wordCntr = 0;
String file1 = path + fileName;
boolean check;
try{
FileInputStream fstream = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while((strLine = br.readLine()) != null){
//check to see whether testWord occurs at least once in the line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if(check){
//get the line, and parse its words into a String array
String[] lineWords = strLine.split("\s+");
for(String w : lineWords)
{
if(w.length() >= tLen){
String word = w.substring(0,tLen).trim();
if(word.equalsIgnoreCase(testWord))
{
wordCntr++;
}
}
}
}
}
System.out.println("total is: " + wordCntr);
//Close the input stream
br.close();
} catch(Exception e){
e.printStackTrace();
}
在我的文本文件中,这个词有 104 次命中。但这不是找到这个词。因为它包含 space 之间。请提出一些建议或在代码本身中进行编辑。
而不是
String[] lineWords = strLine.split("\s+");
做
String[] tokens = strLine.split("(Error: 87)");
然后 (Error: 87)
在该行中出现的次数将是 tokens.length - 1
。