[英]How to search a String Backup = True in a text file
前后之間有一個空格= ...
(Backup = True)------是要搜索的字符串(=之間有空格)
File file = new File(
"D:\\Users\\kbaswa\\Desktop\\New folder\\MAINTENANCE-20150708.log.txt");
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.next();
lineNum++;
String name="Backup = True";
if (line.contains(name)) {
System.out.println("I found "+name+ " in file " +file.getName());
break;
}
else{
System.out.println("I didnt found it");
}
}
}
Scanner.next()
返回下一個完整的令牌,因此它將返回類似Backup
,然后在下一次循環時返回=
在下一次返回true
。
使用Scanner.nextLine()
一次性獲得整行。
scanner.nextLine()
將解決您的問題。 如果您要堅持使用scanner.next()
,則可以定義一個定界符: scanner.useDelimiter("\\n")
讀取文件,直到到達定界符並從那里開始下一個循環。
您需要逐行讀取文件並在每一行中搜索您的字符串。 該代碼應類似於:
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputString)) {
// a match!
System.out.println("Found " +inputString+ " in file ");
break;
}
}
現在確定要在Scanner
還是BufferedReader
之間讀取文件,請檢查此鏈接 。 還要檢查此鏈接以獲取在文件中搜索字符串的快速方法。 完成操作后,也請記住要關閉掃描儀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.