Reputation: 1325
I create text file in my android phone sdcard via filebrowser in pc. Then i try to read it in android app. I get FileNotFoundException - no such path or directory exist
error.
Here is my code
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
is present in root directory of sdcard(i have triple checked). It has some text.
I have given read external storage permission in manifest file.
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>
I tried running the app disconnecting form pc, then too it didn't work showing error. Might be a simple problem. Can anyone explain me where I went wrong?
Upvotes: 0
Views: 711
Reputation: 4656
Try thing. Print the following in log and show us what the path is: sdcard.getPath()
.
Also, use app like ES File explorer to see ur sample.txt
file's property and get the full path. Do they match?
If the path matches, replace this:
File file = new File(sdcard,"sample.txt");
With this:
File file = new File("full_path_of_the_file");
This will help u eliminate where the problem lies.
Good luck.
Upvotes: 1