2012-01-11 158 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()方法。