2016-09-20 52 views
0

我通过pc中的filebrowser在我的android手机sdcard中创建文本文件。然后我尝试在android应用中阅读它。我得到了FileNotFoundException - no such path or directory exist错误。FileNotFoundException尝试从SDCard中读取

这是我的代码

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(); 
    } 

sample.txt存在于SD卡的根目录(我已经三重检查)。它有一些文字。

我在清单文件中给出了读取外部存储权限。

AndroidManifest.xml中

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.bulsy.graphapp"> 
    <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

我试图运行应用程序断开形式的PC,然后也没有奏效示值误差。可能是一个简单的问题。任何人都可以解释我哪里出错了吗?

+2

请再次检查您的interal存储,而不是您的辅助存储(sd卡)sample.txt是否可用。 –

+0

它必须是在SD卡权利?而我调试BufferedReader试图读取'/ storage/sdcard0/sample.txt'产生'Filenotfound'异常 –

回答

1

试试看。在日志中打印以下内容并告诉我们路径是什么:sdcard.getPath()

此外,使用像ES文件资源管理器的应用程序来查看你的sample.txt文件的属性,并获得完整的路径。他们匹配吗?

如果路径匹配,更换此:

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

有了这个:

File file = new File("full_path_of_the_file"); 

这将帮助ü消除问题的症结所在。
祝你好运。

+0

路径是'/storage/sdcard0/sample.txt' –

+0

请尝试以下操作。用'getExternalStorageDirectory(null)'替换'getExternalStorageDirectory()'。看看是否有所作为 –

+0

路径是不同的! ES浏览器说它是'/ storage/sdcard1/sample.txt'!它的工作!当我改变它,如你所说!干杯! –

相关问题