Kris
Kris

Reputation: 3769

Android: Download File code not working

I'm trying to download a file from a URL. My code doesn't return an error but I can't see the file I'm supposed to download in my internal storage. Here's my code:

package com.example.downloadfile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

public class DownloadFile extends Activity {

     private static String fileName = "al.jpg";

     @Override
     public void onCreate(Bundle savedInstanceState) 
     {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = new TextView(this);
        tv.setText("This is download file program... ");

        try {
            URL url = new URL("http://www.fullissue.com/wp-content/uploads/2010/12/Adam-Lambert.jpg");
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = Environment.getDataDirectory() + "/";

            tv.append("\nPath > " + PATH);

            Log.v("log_tag", "PATH: " + PATH);
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, fileName);
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();
        } catch (IOException e) {
            Log.d("log_tag", "Error: " + e);
        }
        Log.v("log_tag", "Check: ");

        tv.append("\nAnother append!");
        this.setContentView(tv);
    }

}

I'm new to java and android dev, any answers would be much appreciated, thanks!


Yo! I used the ff. code instead. This works for me. Thanks for all your help!

private static String fileName = "beautiful_galaxy - tarantula.jpg";
private static String fileURL = "http://apod.nasa.gov/apod/image/0903/tarantula2_hst_big.jpg";

    try {
        File root = Environment.getExternalStorageDirectory();
        URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

        int lenghtOfFile = c.getContentLength();

        FileOutputStream f = new FileOutputStream(new File(root + "/download/", fileName));

        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        long total = 0;

        while ((len1 = in.read(buffer)) > 0) {
            total += len1; //total = total + len1
            //publishProgress("" + (int)((total*100)/lenghtOfFile));
            f.write(buffer, 0, len1);
        }
        f.close();
    } catch (Exception e) {
        Log.d("Downloader", e.getMessage());
    }

Upvotes: 0

Views: 12607

Answers (6)

greenapps
greenapps

Reputation: 11214

You will have a NetworkOnMainThreadException now. Look in the log cat. Place your internet code in an asynctask or thread.

Upvotes: 0

Android
Android

Reputation: 9023

If you are downloading file to Sdcard then make sure that your sdcard is mounted, the code will download file to sdcard, if still getting problem let me know.

try {
            URL url = new URL(provide any URL);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = Environment.getExternalStorageDirectory()
                    + "/download/";
            Log.v(LOG_TAG, "PATH: " + PATH);
            File file = new File(PATH);
            file.mkdirs();

            String fileName = "Test.mp3";


            File outputFile = new File(file, fileName);
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {

                fos.write(buffer, 0, len1);

            }
            fos.close();
            is.close();

            // }
        } catch (IOException e) {
            Log.d(LOG_TAG, "Error: " + e);
            Toast.makeText(myApp, "error " + e.toString(), Toast.LENGTH_LONG)
                    .show();

        }


best of luck :)

Upvotes: 3

Ashish Anand
Ashish Anand

Reputation: 3581

Check the following permissions in Manifest file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Upvotes: 0

Redax
Redax

Reputation: 9231

To download a file I use the following code:

public boolean 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 false; 
  } 
catch (IOException e) 
  {
  return false; 
  }

return true;
}

Upvotes: -2

Femi
Femi

Reputation: 64690

Pretty sure (like @dmon said) that you can't write to the data directory in that fashion. You want to:

  1. Use Environment.getDownloadCacheDirectory () or Environment.getExternalStorageDirectory (). Take a look at the javadoc for http://developer.android.com/reference/android/os/Environment.html#getDataDirectory%28%29.
  2. Using URLConnection() is fine: this is standard java, and works just fine.
  3. What do the android logs say?

Upvotes: 0

Asher
Asher

Reputation: 1867

I saw this talk and the guy said you should use the Apache HTTP client and not the java one

Here is a code snippet take from the tutorial:

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
    InputStream instream = entity.getContent();
    int l;
    byte[] tmp = new byte[2048];
    while ((l = instream.read(tmp)) != -1) {
    }
}

Upvotes: 0

Related Questions