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

时间:2009-11-11 12:00:20

标签: android

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

这是我的代码:

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

5 个答案:

答案 0 :(得分:37)

这是我用于将给定URL下载到给定File对象的一些工作代码。刚刚使用新文件(路径)创建了File对象(outputFile),我还没有调用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
  }
}

答案 1 :(得分:5)

权限

<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" />

下载功能代码

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

答案 2 :(得分:3)

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

    }

答案 3 :(得分:2)

我检查了this stackoverflow question,但看起来没有下载Intent。

您是否尝试在Android清单中设置WRITE_EXTERNAL_STORAGE

答案 4 :(得分:0)

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

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

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