how to save a file in android, ENOENT IOexception -
how save file in android? have following code:
final file file = new file(cont.getexternalfilesdir(null), filename); if (!file.exists()) { file.createnewfile(); }
and
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): @ java.io.file.createnewfile(file.java:948)
exception complete code saving of file 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(); } { output.close(); } log.i("save_file", "save disk ok"); } catch (exception e) { e.printstacktrace(); }
i have permissions:
<uses-permission android:name="android.permission.read_external_storage" /> <uses-permission android:name="android.permission.write_external_storage" />
can 1 please point out i'm doing wrong, thanks
edited: problem name of file wanted save, shouldn't contain restricted chars, mine in format:"xxx/xxx.jpg"
'/' not valid char file name. thanks
better use environment.getexternalstoragedirectory() instead of context.getexternalfilesdir(null) though seems same.
here code:
string extr = environment.getexternalstoragedirectory().tostring(); file mfolder = new file(extr + "/mainfolder_photo"); if (!mfolder.exists()) { mfolder.mkdir(); } string strf = mfolder.getabsolutepath(); msubfolder = new file(strf + "/pictures"); if (!msubfolder.exists()) { msubfolder.mkdir(); } // check file there or not;// if present delete try { file yourdir = new file(msubfolder.getabsolutefile().tostring()); (file f : yourdir.listfiles()) { if (f.length()>0){ f.delete(); } } } catch (exception e) { // todo: handle exception } // file name string s = "puzzle_photo.png"; file f = new file(msubfolder.getabsolutepath(), s); strmyimagepath = f.getabsolutepath(); outputstream output; try { output = new fileoutputstream(f); url url = new url("file://" + filepath);// data inputstream input = url.openstream(); byte[] buffer = new byte[1024]; int bytesread = 0; while ((bytesread = input.read(buffer, 0, buffer.length)) >= 0) { output.write(buffer, 0, bytesread); } output.close(); input.close(); return true; } catch (exception e) { e.printstacktrace(); }
Comments
Post a Comment