在 Android 上以编程方式下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1714761/
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-08-20 03:30:25  来源:igfitidea点击:

Download a file programmatically on Android

android

提问by mudit

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.

我正在以编程方式从 Web 服务器下载文件。下载完成后,我检查了文件。大小、扩展名和所有其他参数都是正确的,但是当我尝试在媒体播放器中播放该文件时,它显示它已损坏。

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

回答by Eric Mill

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.

这是我用于将给定 URL 下载到给定 File 对象的一些工作代码。File 对象 (outputFile) 刚刚使用 new File(path) 创建,我没有调用 createNewFile 或任何东西。

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

回答by Sachin Yadav

Permission

允许

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />

Download Fuction Code

下载功能代码

 public void downloadFile() {
        String DownloadUrl = audio1;
        DownloadManager.Request request1 = new DownloadManager.Request(Uri.parse(DownloadUrl));
        request1.setDescription("Sample Music File");   //appears the same in Notification bar while downloading
        request1.setTitle("File1.mp3");
        request1.setVisibleInDownloadsUi(false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            request1.allowScanningByMediaScanner();
            request1.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        }
        request1.setDestinationInExternalFilesDir(getApplicationContext(), "/File", "Question1.mp3");

        DownloadManager manager1 = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Objects.requireNonNull(manager1).enqueue(request1);
        if (DownloadManager.STATUS_SUCCESSFUL == 8) {
        DownloadSuccess(); 
        }
    }

回答by BasavRaj

private void down(String string)
    {

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

            String PATH = Environment.getExternalStorageDirectory().toString()
                    + "/load";
            Log.v("LOG_TAG", "PATH: " + PATH);

            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, option14[i].toString());
            FileOutputStream fos = new FileOutputStream(outputFile);
            InputStream is = c.getInputStream();

            byte[] buffer = new byte[4096];
            int len1 = 0;

            while ((len1 = is.read(buffer)) != -1)
            {
                fos.write(buffer, 0, len1);
            }

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

            Toast.makeText(this, " A new file is downloaded successfully",
                    Toast.LENGTH_LONG).show();

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }

回答by Macarse

I checked this stackoverflow questionbut it looks like there is not a download Intent.

我检查了这个 stackoverflow 问题,但看起来没有下载意图。

Did you try setting the WRITE_EXTERNAL_STORAGEin the android manifest?

您是否尝试在 android manifest 中设置WRITE_EXTERNAL_STORAGE

回答by haseman

read on an input stream doesn't guarntee that the entire contents of the file will be pulled down in one go. Check the return value on that in.read(b); line. It might look something like this:

在输入流上读取并不能保证文件的全部内容将被一次性拉下来。检查 in.read(b); 上的返回值;线。它可能看起来像这样:

if(in.read(b) != size)
    Log.e("Network","Failed to read all data!");

That'll tell you, at the very least, if you're getting all your data from the networking layer. If you only got a partial read, but you're still writing the full byte array to disk, that might explain why the media player thinks the file is corrupt.

这至少会告诉您,您是否从网络层获取所有数据。如果您只读取了部分内容,但您仍在将完整字节数组写入磁盘,这可能解释了媒体播放器认为文件已损坏的原因。