2012-01-11 76 views
-3

可以說我有一個字符串=「你好」。我如何打開一個文本文件並檢查該文本文件中是否存在你好?該文本文件的在分隔文本中搜索字符串文件

內容:

hello:man:yeah 

我嘗試使用下面的代碼。它是隻讀文件的第一行嗎?我需要它來檢查所有行,看看你是否存在,然後如果是這樣,請從中取出「man」。

try { 
    BufferedReader in = new BufferedReader(new FileReader("hello.txt")); 
    String str; 
    while ((str = in.readLine()) != null) { 
     System.out.println(str); 
    } 
} catch (IOException e) { 
    System.out.println("Error."); 
} 
+1

'字符串myArray的[] = str.split(「:」);'在java [String](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html)類中有許多方法這些類型的東西。 – 2012-01-11 14:46:40

+2

你的文件只包含一行......所以readline在讀取該行時比離開循環,因爲第二次in.readline返回null – Hons 2012-01-11 14:47:14

+0

你對BufferedReader的使用看起來是正確的。你沒有看到「hello.txt」的逐行輸出嗎? – dasblinkenlight 2012-01-11 14:47:57

回答

4

如果你好:man:是你的文件中的一行,那麼你的代碼是正確的。 readLine()將讀取一行,直到找到換行符(在這種情況下爲一行)。

如果你只是想看看它是否在該文件中,那麼你可以做這樣的事情:

String str; 
boolean found = false; 
while ((str = in.readLine()) != null) { 
     if(str != null && !found){ 
     found = str.contains("hello") ? true : false; 
     } 
    } 

如果你需要做一個整體詞搜索,你需要使用正則表達式。用\ b圍繞搜索文本將執行整個單詞搜索。這裏有一個片段(注意,StringUtils的來自Apache的百科全書郎):

List<String> tokens = new ArrayList<String>(); 
    tokens.add("hello"); 

    String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b"; 
    Pattern pattern = Pattern.compile(patternString); 
    Matcher matcher = pattern.matcher(text); 

    while (matcher.find()) { 
     System.out.println(matcher.group(1)); 
    } 

當然,如果你不具備多個令牌,你可以這樣做:

String patternString = "\\bhello\\b"; 
+0

嗨,謝謝。使用String.contains,即使輸入是「hell」,它也會返回true。我需要它是確切的。 – 2012-01-11 14:58:59

+0

我從這裏取消了字符串匹配的東西:http://stackoverflow.com/questions/5091057/how-to-find-a-whole-word-in-a-string-in-java。 – Dave 2012-01-11 15:15:16

1

在每行上使用String.contains方法。每行都在while循環中處理。

1

使用String.indexOf()String.contains()方法。