我通過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'異常 –