android - How to download file and store in sdcard? -
i working on should download file server , store in sdcard .
but getting exception : java.io.filenotfoundexception (permission denied)
public class mainactivity extends actionbaractivity { // usually, subclasses of asynctask declared inside activity class. // way, can modify ui thread here private class downloadtask extends asynctask<string, integer, string> { private context context; private powermanager.wakelock mwakelock; file file,sdcard; public downloadtask(context context) { this.context = context; } @override protected string doinbackground(string... surl) { system.out.print("background"); inputstream input = null; outputstream output = null; httpurlconnection connection = null; try { url url = new url(surl[0]); connection = (httpurlconnection) url.openconnection(); connection.connect(); // expect http 200 ok, don't mistakenly save error report // instead of file if (connection.getresponsecode() != httpurlconnection.http_ok) { return "server returned http " + connection.getresponsecode() + " " + connection.getresponsemessage(); } // useful display download percentage // might -1: server did not report length int filelength = connection.getcontentlength(); // download file input = connection.getinputstream(); ' getting exception in line ' output = new fileoutputstream("sdcard/file.mp3"); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { // allow canceling button if (iscancelled()) { input.close(); return null; } total += count; // publishing progress.... if (filelength > 0) // if total length known publishprogress((int) (total * 100 / filelength)); output.write(data, 0, count); } } catch (exception e) { return e.tostring(); } { try { if (output != null) output.close(); if (input != null) input.close(); } catch (ioexception ignored) { } if (connection != null) connection.disconnect(); } return null; }
try this
file root = new file(environment.getexternalstoragedirectory(), "file.mp3"); if (!root.exists()) { root.mkdirs(); } output = new fileoutputstream(root);
and add permission on manifest file as
<uses-permission android:name="android.permission.write_external_storage" />
Comments
Post a Comment