How to save a file in android? I have the following code:
final File file = new File(cont.getExternalFilesDir(null), filename);
if (!file.exists()) {
file.createNewFile();
}
and I get
03-21 11:31:29.903: W/System.err(31668): java.io.IOException: open failed: ENOENT (No such file or directory)
03-21 11:31:29.903: W/System.err(31668): at java.io.File.createNewFile(File.java:948)
exception My complete code for the saving of the file is the following:
final File file = new File(context.getExternalFilesDir(null), filename);
if (!file.exists()) {
// file.mkdirs();
file.createNewFile();
}
final OutputStream output = new FileOutputStream(file);
try {
try {
final byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) != -1)
output.write(buffer, 0, read);
output.flush();
} finally {
output.close();
}
Log.i("save_file", "save to disk is ok");
} catch (Exception e) {
e.printStackTrace();
}
I also have the permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Can some one please point out what I'm I doing wrong, thanks
EDITED:
The problem was the name of the file that i wanted to save, so it shouldn't be contain restricted chars, mine was in this format:"xxx/xxx.jpg" so '/' is not a valid char for a file name. Thanks
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) before context.getExternalFilesDir(null)