Android:下载文件代码不起作用

时间:2011-05-04 03:40:20

标签: java android file url download

我正在尝试从网址下载文件。我的代码没有返回错误,但我看不到我应该在内部存储中下载的文件。这是我的代码:

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);
    }

}

我是java和android dev的新手,任何答案都会非常感谢,谢谢!


哟!我用的是ff。代码而不是。这适合我。谢谢你的帮助!

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());
    }

6 个答案:

答案 0 :(得分:3)

如果您要将文件下载到Sdcard,请确保已安装了SD卡,代码会将文件下载到SD卡,如果仍有问题请告诉我。

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();

        }


祝你好运:)

答案 1 :(得分:0)

我看到了这个talk,那个人说你应该使用Apache HTTP client而不是java一个

以下是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) {
    }
}

答案 2 :(得分:0)

非常确定(如@dmon所说)你不能以这种方式写入数据目录。你想要:

  1. 使用Environment.getDownloadCacheDirectory ()Environment.getExternalStorageDirectory ()。看一下http://developer.android.com/reference/android/os/Environment.html#getDataDirectory%28%29的javadoc。
  2. 使用URLConnection()很好:这是标准的java,并且工作得很好。
  3. android日志说什么?

答案 3 :(得分:0)

检查清单文件中的以下权限:

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

答案 4 :(得分:0)

您现在将拥有NetworkOnMainThreadException。看看日志猫。将您的互联网代码放在asynctask或线程中。

答案 5 :(得分:-2)

要下载文件,请使用以下代码:

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;
}