Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a file programmatically on Android

Tags:

android

I am downloading files from web server programmatically. After download is completed, I checked the file. The size ,extension and all other parameters are correct but when I try to play that file in media player it is showing that it is corrupted.

Here is my code:

    byte[] b = null;     InputStream in = null;     b = new byte[Integer.parseInt(size)];    // size of the file.     in = OpenHttpConnection(URL);                 in.read(b);     in.close();      File folder = new File("/sdcard", "folder");    boolean check = folder.mkdirs();     Log.d("HttpDownload", "check " + check);     File myFile = new File("/sdcard/folder/" + name);       myFile.createNewFile();    OutputStream filoutputStream = new FileOutputStream(myFile);     filoutputStream.write(b);     filoutputStream.flush();     filoutputStream.close(); 
like image 512
mudit Avatar asked Nov 11 '09 12:11

mudit


People also ask

How do I download files on Android?

Go to the webpage where you want to download a file. Touch and hold what you want to download, then tap Download link or Download image. To see all the files you've downloaded to your device, open the Downloads app. Learn more about managing downloaded files.

How do I use Download Manager on Android?

If you want to download large files/streaming you can use Android Download Manager. The download manager handles HTTP connections, monitors connectivity changes, reboots, and ensures each download completes successfully. First, we will have to generate URI from URL.

How download video from URL in android programmatically?

Step 1: Create an android project with an empty Activity. Start your android studio and create a project in with select an empty activity. and used a button in your XML file and findviewbyid in your main java file, Android download video from URL and save to internal storage.


1 Answers

This is some working code I have for downloading a given URL to a given File object. The File object (outputFile) has just been created using new File(path), I haven't called createNewFile or anything.

private static void downloadFile(String url, File outputFile) {   try {       URL u = new URL(url);       URLConnection conn = u.openConnection();       int contentLength = conn.getContentLength();        DataInputStream stream = new DataInputStream(u.openStream());          byte[] buffer = new byte[contentLength];         stream.readFully(buffer);         stream.close();          DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));         fos.write(buffer);         fos.flush();         fos.close();   } catch(FileNotFoundException e) {       return; // swallow a 404   } catch (IOException e) {       return; // swallow a 404   } } 
like image 177
Eric Mill Avatar answered Oct 18 '22 01:10

Eric Mill