如何从android中的txt文件中读取特定文本

时间:2014-02-28 17:44:22

标签: java android

我正在尝试创建一个简单的字典,用于搜索txt文件中的单词。我创建了txt文件并存储了一些英文单词。我想把这个词写到EditText。然后,将在TextView上找到并显示该单词。这是我的代码。它显示整个txt文件。我怎样才能找到具体的单词?

public class MainActivity extends Activity {

//creating variables
TextView myText;
EditText myEdit;
Button myButton;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //initializing the TextView EditText and Button
    myText=(TextView) findViewById(R.id.idTextView);
    myEdit=(EditText) findViewById(R.id.idEditText);
    myButton=(Button) findViewById(R.id.idButton);


    myButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String saveData=myEdit.getText().toString();
            try{
            myText.setText(readfile());
            }catch(IOException e){
                e.printStackTrace();
            }

        }

    });

}

private String  readfile()throws IOException {     

    String str="";          
    InputStream is = getResources().openRawResource(R.raw.translate);    
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    String line=reader.readLine();

    while (line!=null)
    {   
        str = str + line + "\n";
        line = reader.readLine();

    }
    reader.close();

    return str;

}

}

2 个答案:

答案 0 :(得分:1)

认为你正在进行简单的contains()检查:

String fileText = readFile();

Boolean textFound = fileText.contains(saveData);

如果该布尔值为true,那么您将在框中显示saveData的值。如果需要,您可以将此操作放在循环中并搜索多个单词。

答案 1 :(得分:1)

这完全取决于readFile()的实施方式。我建议您修改它以接受String参数。这样,它将在文件中搜索该单词并将其含义作为另一个String返回,您可以通过TextView

将其分配给setText()
myText.setText(readFile(saveData)));  

是建议的实现的样子。


在此方法中,当您逐行读取文件时,请检查刚刚从文件中读取的String是否包含所需的单词。这可以使用contains()方法完成。

相关问题