Android- Saving File (Input & Output Stream) throws Exception (open failed: EINVAL (Invalid argument)) in Pre-lollipop devices
I am downloading a file from URL (www.xyz.in/file/9
) and saving in SD CARD.
Folder created code:
try {
//String folder_name = "NewFolder";
File f = new File(Environment.getExternalStorageDirectory(), "Venky");
if (!f.exists()) {
f.mkdirs();
}
} catch (Exception e) {
Log.v("MTV", " createFileDirectory exception" + e);
}
Below I posted a (Download and Saving file) code, In android lollipop, It works fine to download and saved the file in SD Card.
it doesn't works on Pre-lolipop devices. It throws Exception.
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
String depo = conection.getHeaderField("Content-Disposition");
String depoSplit[] = depo.split("filename=");
filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
filename=filename.trim();
String Filetype = conection.getContentType();
Log.v("fileName", " " + filename + " FileLength " + lenghtOfFile + " Filetype " + Filetype);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/Venky/" + filename);
Log.v("", "" + Environment.getExternalStorageDirectory().toString() + "/" + R.string.app_name + "/" + filename);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
DownloadSucess = true;
} catch (Exception e) {
DownloadSucess = false;
Log.e("Error: ","Download Exception "+ e);
}
return null;
}
Logcat (Exception):
>E/Error:: Download Exception java.io.FileNotFoundException: /storage/sdcard0/Venky/FileName : smile-please.png: open failed: EINVAL (Invalid argument)
Note: In manifest, Both WRITE_EXTERNAL_STORAGE
& READ_EXTERNAL_STORAGE
permissions are used.
The value of your variable filename
is FileName : smile-please.png
and not -what you think- smile-please.png
.
Just log the contents of filename before use.