I want to create a file in external storage sdCard and write to it.I have searched through internet and try but not getting the result,I have added permission in Android Manifest file as well,I am doing this on Emulator,I am trying the following code and getting a ERRR", "Could not create file".
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
//private Throwable e;
@Override
public void onClick(View v) {
// write on SD card file data from the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
} catch (Exception e) {
Log.e("ERRR", "Could not create file",e);
}
}// onClick
}); // btnWriteSDFile
I know this is a bit late but i have don it this way, it creates a Documents directory and then a sub-directory for the application and saved the files to it.
This one creates the file name
Hop this helps some one took me a long time to work it out and get it working.
You can do this with this code also.
To write into external storage in Lollipop+ devices we need:
Add the following permission into Manifest:
Request an approval from the user:
Handle the user response inside Activity:
Even though above answers are correct, but I wanna add a notice to distinguish types of storage:
Here is the link to a source code for cases I mentioned above: https://github.com/mttdat/FileUtils
You can find these method usefull in reading and writing data in android.