通过eclipse Android从外部存储目录中读取文本文件

时间:2015-02-10 21:48:06

标签: java android eclipse file txtextcontrol

我在Android中的ExternalStorageDirectory()中有一个.txt文件。该文件逐行包含10个句子。我想逐一阅读每个句子。然后在每个按钮点击时在EditText上显示它。我发现只有所有文件读取代码。我不想要这个。我怎样才能做到这一点?这是我的小代码:

enter cod private String Load() {
    String result = null;;
    String FILE_NAME = "counter.txt";
    //if (isExternalStorageAvailable() && isExternalStorageReadOnly()) {
        String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "Records";
        File file = new File(baseDir, FILE_NAME);

        String line = "";
        StringBuilder text = new StringBuilder();

        try {
            FileReader fReader = new FileReader(file);
            BufferedReader bReader = new BufferedReader(fReader);

            while( (line = bReader.readLine()) != null  ){
                text.append(line+"\n");
            }
            result = String.valueOf(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
    //}
    return result;
}

1 个答案:

答案 0 :(得分:0)

所有Load()都会读取文件并将其作为String返回。从这里,你有几个选择。

1)。 使用String.split(' \ n')将结果转换为字符串数组,并在单击按钮时获取下一个值。这是一个简单的例子:

int counter = 0;
String file = Load();
String[] lines = file.split("\n");

button.onClicked() {
    editText.setText(lines[counter++]);
}

2)。 将缓冲的阅读器声明为类成员,因此您可以在按钮的onClicked()方法中调用readLine()。这样,当有人点击按钮时,它只会读取文件的一行,而不是在Load()中读取整个文件。

相关问题