在java中搜索文本文件
所以我试图搜索一个文本文件,如果找到了用户输入,它会返回整个句子,包括空格。但显然我只得到第一个字符串,没有任何东西能传递句子中的第一个字符串。例如,如果我有一个名为“data.txt”的文本文件,第一行的内容是“我是一个图例”。用户输入“我是图例”后,搜索文件后的输出为“I”。任何帮助都将不胜感激在java中搜索文本文件,java,search,text-files,Java,Search,Text Files,所以我试图搜索一个文本文件,如果找到了用户输入,它会返回整个句子,包括空格。但显然我只得到第一个字符串,没有任何东西能传递句子中的第一个字符串。例如,如果我有一个名为“data.txt”的文本文件,第一行的内容是“我是一个图例”。用户输入“我是图例”后,搜索文件后的输出为“I”。任何帮助都将不胜感激 public static void Findstr() { // This function searches the text for the string File file
public static void Findstr() { // This function searches the text for the string
File file = new File("data.txt");
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
Scanner scanner;
try {
scanner = new Scanner(file).useDelimiter( ",");
while (scanner.hasNext()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(name)) {
// a match!
System.out.println("I found " + name);
break;
}
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
Scanner.next()使用Scanner.readLine()返回下一个字符代码>
编辑:
相信扫描仪使用.nextLine()代码>非.readLine()代码>当您扫描输入时
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
您只接受一个令牌。您应该使用kb.nextLine()
上面的代码不区分大小写进行搜索。您应该使用nextLine()获取完整的行。next()在空白处中断
参考:
如果你提到“data.text”文件中的几行,那就更好了。没关系,我已经解决了这个问题。问题发生在kb.next()。它应该是kb.nextLine()。如何使用scanner来解析文件,而不是一些字符串()“am”。在上面的示例中,am是搜索字符串。你可以用你想要的任何东西来代替它。您还可以要求用户为您输入一个字符串,并将其作为参数传递到方法中。public static void parseFile(String fileName,Scanner searchStr)抛出FileNotFoundException{Scanner scan=new Scanner(new File(fileName));而(scan.hasNext()){String line=scan.nextLine().toLowerCase().toString();if(line.contains(searchStr)){System.out.println(line)函数parseFile的参数是两个字符串对象。您不能将扫描仪传递给它。如果要通过扫描仪,则必须将方法的定义更改为:public void parseFile(字符串文件名、字符串searchStr、扫描仪扫描仪)throws FileNotFoundExceptionScanner中没有文本。Scanner是解析文件的助手类。为什么不能在parse函数中定义scanner?
package com.example;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileSearch {
public void parseFile(String fileName,String searchStr) throws FileNotFoundException{
Scanner scan = new Scanner(new File(fileName));
while(scan.hasNext()){
String line = scan.nextLine().toLowerCase().toString();
if(line.contains(searchStr)){
System.out.println(line);
}
}
}
public static void main(String[] args) throws FileNotFoundException{
FileSearch fileSearch = new FileSearch();
fileSearch.parseFile("src/main/resources/test.txt", "am");
}
}
test.txt contains:
I am a legend
Hello World
I am Ironman
Output:
i am a legend
i am ironman