尝试从SDCard读取时出现FileNotFoundException

时间:2016-09-20 12:36:39

标签: android file bufferedreader sd-card

我通过pc中的filebrowser在我的android手机sdcard中创建文本文件。然后我尝试在Android应用程序中阅读它。我收到foreach($navigation as $n) { if(ucfirst($explode('.', $pageName) == $n) { echo '<li class="active"><a href="' . $n . '">' . ucfirst($n) . '</a></li>'; } else { echo '<li><a href="' . $n . '">' . ucfirst($n) . '</a></li>'; } } 错误。

这是我的代码

FileNotFoundException - no such path or directory exist

private String readFromFile(Context context) { StringBuilder text = new StringBuilder(); String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { File sdcard = Environment.getExternalStorageDirectory(); File file = new File(sdcard,"sample.txt"); //Read text from file try { //File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "sample.txt"); BufferedReader br = new BufferedReader(new FileReader(file));//Error occurs here String line; Toast.makeText(context, "success!", Toast.LENGTH_LONG).show(); while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } br.close(); } catch (IOException e) { e.getMessage(); Toast.makeText(context, "Error!", Toast.LENGTH_LONG).show(); //You'll need to add proper error handling here } } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write } return text.toString(); } 出现在sdcard的根目录中(我已经检查了三次)。它有一些文字。

我已在清单文件中提供了读取外部存储权限。

的AndroidManifest.xml

sample.txt

我尝试运行应用程序断开连接PC,然后它也没有显示错误。可能是一个简单的问题。有谁能解释我哪里出错了?

1 个答案:

答案 0 :(得分:1)

尝试一下。在日志中打印以下内容并向我们显示路径:sdcard.getPath()

此外,使用ES文件资源管理器等应用查看您的sample.txt文件的属性并获取完整路径。他们匹配吗?

如果路径匹配,请替换此:

File file = new File(sdcard,"sample.txt");

有了这个:

File file = new File("full_path_of_the_file");

这将有助于你消除问题所在 祝你好运。