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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5878241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:14:46  来源:igfitidea点击:

Android: Download File code not working

javaandroidfileurldownload

提问by Kris

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:

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

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!

我是java和android dev的新手,任何答案将不胜感激,谢谢!



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

哟!我用过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());
    }

回答by Android

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.

如果您要将文件下载到 Sdcard,请确保您的 sdcard 已挂载,代码会将文件下载到 sdcard,如果仍有问题,请告诉我。

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 :)

祝你好运:)

回答by Ashish Anand

Check the following permissions in Manifest file:

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

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

回答by greenapps

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

现在您将有一个 NetworkOnMainThreadException。查看日志猫。将您的 Internet 代码放在异步任务或线程中。

回答by Asher

I saw this talkand the guy said you should use the Apache HTTP clientand not the java one

我看到了这个演讲,那个人说你应该使用Apache HTTP 客户端而不是 java客户端

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

回答by Femi

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

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

  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?
  1. 使用Environment.getDownloadCacheDirectory ()Environment.getExternalStorageDirectory ()。查看http://developer.android.com/reference/android/os/Environment.html#getDataDirectory%28%29的 javadoc 。
  2. 使用 URLConnection() 很好:这是标准的 Java,并且工作正常。
  3. android日志说什么?

回答by Redax

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