0

我目前正在 sd 卡中搜索任何文件类型.csv.txt。我将这些文件的行显示为敬酒。我现在只想显示包含已定义关键字的行。在我看来,我应该使用RuleBasedCollat​​or,但我不确定如何实现它。

这是我应该这样做的正确方法还是有另一种更好的解决方案?

谢谢

代码(我已经评论了if我的问题所在的第二个):

    private void conductScan() {

    File[] file = Environment.getExternalStorageDirectory().listFiles();  


    for (File f : file)
    {
       if (f.isFile() && f.getPath().endsWith(".xml") || f.getPath().endsWith(".txt")) {
           StringBuilder text = new StringBuilder();
           try {
               BufferedReader br = new BufferedReader(new FileReader(f));
               String line;
               while ((line = br.readLine()) != null) {
                   text.append(line);
                   text.append('\n');
                   if (line ) {  //here I want to define if line contains "test" then show the toast"
                       Toast.makeText(getApplicationContext(),line,Toast.LENGTH_LONG).show();
                       } else {
                           Toast.makeText(getApplicationContext(),"No keyewords found",Toast.LENGTH_LONG).show();
                       }
                   }
               }
           catch (IOException e) {
               Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
           }
               String [] mStrings=text.toString().split("\n");
       }

    }
}
4

1 回答 1

3

要检查该行是否包含子字符串,您可以使用:

public boolean contains(CharSequence s)

类的String

不确定这是否是问题所在。这样做的问题是,您的循环将非常快地遍历行,并且您将无法看到消息。

您可以将这些行打印到Log或另一个文本文件中,以便稍后对其进行分析。

编辑:

你可以改变这部分:

while ((line = br.readLine()) != null) 
{
    //be careful! with this, you will add all the lines of
    //the currently processed file to a locally created 
    //StringBuilder object. Is this really what you want?
    text.append(line);
    text.append('\n');

    //here if line contains "test" you can do whatever you want with it.
    if (line.contains("test")) 
    {
        //do something with it
    }
    else
    {
        //no "test" keyword in the current line
    }
}
于 2012-08-31T19:50:45.647 回答