Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java根据第一个单词查找文件中的特定行_Java - Fatal编程技术网

java根据第一个单词查找文件中的特定行

java根据第一个单词查找文件中的特定行,java,Java,我有一个要导入的文件,我要做的是请求用户的输入,并将其用作找到要检查的正确行的基础。我把它设置成这样: public class ReadLines { public static void main(String[] args) throws FileNotFoundException { File fileNames = new File("file.txt"); Scanner scnr = new Scanner(fileNames)

我有一个要导入的文件,我要做的是请求用户的输入,并将其用作找到要检查的正确行的基础。我把它设置成这样:

     public class ReadLines {
    public static void main(String[] args) throws FileNotFoundException
    {
         File fileNames = new File("file.txt");
     Scanner scnr = new Scanner(fileNames);
     Scanner in = new Scanner(System.in);

    int count = 0;
    int lineNumber = 1;

    System.out.print("Please enter a name to look up: ");
    String newName = in.next();

    while(scnr.hasNextLine()){
          if(scnr.equals(newName))
          {
              String line = scnr.nextLine();
              System.out.print(line);
          }
      } 
}
现在,我只是想把它打印出来,看看我是否已经捕获了它,但这不起作用。有人有什么想法吗?另外,如果有关系,我不能使用try-and-catch或数组。
非常感谢

您需要将该行缓存在局部变量中,以便以后打印出来。像这样的事情应该可以做到:

while(scnr.hasNextLine()){
    String temp = scnr.nextLine(); //Cache variable
    if (temp.startsWith(newName)){ //Check if it matches
        System.out.println(temp); //Print if match
    }
}

希望这有帮助

我会做以下几行:

Scanner-in=新的扫描仪(System.in);
System.out.print(“请输入要查找的名称:”);
字符串名称=in.next();
列表行=Files.readAllLineS(新文件(“File.txt”).toPath(),StandardCharsets.UTF_8);
可选的firstResult=lines.stream().filter(s->s.startsWith(name)).findFirst();
if(firstResult.isPresent){
System.out.print(“行:+firstResult.get());
}否则{
系统输出打印(“未找到”);
}   

您可以使用我想您应该使用
sncr.findInLine
API,而不是
equals
非常感谢您的帮助!这两个都很棒!