I want to write a file to external storage in android but get the FileNotFoundException. I have put the permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
in my manifest and if I do a check like
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
it returns true. I have tried different solutions from questions from SO (Android saving file to external storage; Write a file in external storage in Android; Writing to external storage filenotfoundexception) but none seemed to work for me. Sorry for posting a duplicate question but Ive been searching for days and couldnt find an answer.
My Code is the following:
private void Writing(String erg) {
TextView one = (TextView) findViewById(R.id.e1);
File root = android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File dir = new File (root.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, "Test.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(erg);
pw.flush();
pw.close();
f.close();
one.setText("File created");
} catch (FileNotFoundException e) {
e.printStackTrace();
one.setText("Error1");
} catch (IOException e) {
e.printStackTrace();
one.setText("Error2");
}
}
The Textview one ends up with printing Error1.
I'll appreciate any help.