我通过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,然后也没有奏效示值误差。可能是一个简单的问题。任何人都可以解释我哪里出错了吗?
请再次检查您的interal存储,而不是您的辅助存储(sd卡)sample.txt是否可用。 –
它必须是在SD卡权利?而我调试BufferedReader试图读取'/ storage/sdcard0/sample.txt'产生'Filenotfound'异常 –