在android中读取文本文件

时间:2017-10-11 20:05:02

标签: java android

我正在尝试读取存储在我的移动设备外部存储中的文本文件,但它会抛出此错误: -    读取文本文件时出错!! / storage / emulated / 0 / atom.txt:打开失败:ENOENT(没有这样的文件或目录) 这是代码

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.btn_picker);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            try {
                fileOpener();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

}

private void fileOpener() throws IOException {
    File sdcard = Environment.getExternalStorageDirectory();

    //Get the text file
    File file = new File(sdcard,"atom.txt");
    //Read text from file
    StringBuilder text = new StringBuilder();

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
    }
    catch (IOException e) {

        Log.e("Error", "Error occured while reading text file!!" + e.getMessage());
    }

    //Find the view by its id
  Log.d("Text",text.toString());
} 

}

我怎么能弄清楚这一点?
编辑:atom.txt文件已保存在我的设备中,但仍然会抛出相同的错误。

1 个答案:

答案 0 :(得分:0)

该文件不存在,因此Environment.getExternalStorageDirectory返回的路径不是您期望的路径。根据{{​​3}},此路径不能保证是SD卡。

相关问题