2015-11-19 23 views
1

我有一个文件,我正在导入,我想要做的是要求用户的输入,并将其用作查找要检查的正确行的基础。我有它设置如下:java根据第一个字找到文件中的特定行

 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和catch或数组。 非常感谢!

+1

您可以使用['String.startsWith()'](http://docs.oracle.com/javase/7/docs/api /java/lang/String.html#startsWith(java.lang.String)) – alfasin

+0

我想你想使用'sncr.findInLine' API,而不是'equals' –

+0

非常感谢您的帮助!这两个都很棒! – Vaak

回答

1

您需要将行缓存在本地变量中,以便稍后打印出来。像这样的应该做的伎俩:

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

希望这会有所帮助!

+0

非常感谢!这完美的作品! – Vaak

0

我做的东西线:

Scanner in = new Scanner(System.in); 

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

List<String> lines = Files.readAllLineS(new File("file.txt").toPath(), StandardCharsets.UTF_8); 
Optional<String> firstResult = lines.stream().filter(s -> s.startsWith(name)).findFirst(); 

if (firstResult.isPresent) { 
    System.out.print("Line: " + firstResult.get()); 
} else { 
    System.out.print("Nothing found"); 
} 
相关问题