从多种文件类型中解析文本

时间:2012-08-31 19:46:30

标签: java android text

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

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

由于

代码(我已对第二个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");
       }

    }
}

1 个答案:

答案 0 :(得分: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
    }
}