PCのファイルブラウザ経由でアンドロイド電話のsdcardにテキストファイルを作成します。それから私はアンドロイドアプリでそれを読み取ろうとします。私はFileNotFoundException - no such path or directory exist
エラーが発生します。ここでSDCardからの読み込み中にFileNotFoundExceptionが発生しました
は私のコードは
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を実行してみました。簡単な問題かもしれません。誰かが私がどこに間違っていたか説明できますか?
あなたのセカンダリストレージ(sdカード)ではなく、sample.txtが使用可能かどうかを再度確認してください。 –
これはsdcardに正しくなければなりませんか?私はBufferedReaderが '/ storage/sdcard0/sample.txt'から' Filenotfound'例外を読み込もうとしている間にデバッグしています –