2013-02-23 34 views
1

正如我的標題所示。我需要通過文件搜索字符串。找到它時,我需要下一行。 是這樣的文件:在文件中搜索字符串並返回下一行(用Java)

你好

世界

當 「你好」 被發現, 「世界」 需要返回。

File file = new File("testfile"); 
Scanner scanner = null; 
try { 
    scanner = new Scanner(file); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} 

if (scanner != null) { 
    String line; 
    while (scanner.hasNextLine()) { 
    line = scanner.nextLine(); 
    if (line == "hello") { 
     line = scanner.nextLine(); 
     System.out.println(line); 
    } 
    } 
} 

它通過文件讀取,但沒有找到單詞「hello」。

+1

可能重複(HTTP的:/ /stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – jlordo 2013-02-23 20:17:35

回答

5
if (line == "hello") { 

應該

if ("hello".equals(line)) { 

你必須使用equals()方法來檢查兩個字符串對象是相等的。 ==運算符在String(和所有對象)的情況下僅檢查兩個引用變量是否引用同一個對象。

1
if (line == "hello") 

應改爲

if (line.contains("hello")) 
0

而不是使用==運算符來比較兩個字符串使用 if(line.compareTo("hello") == 0)

的[我如何在Java中比較字符串?]
相關問題