2012-10-03 66 views
0

在我的應用程序,我有要求從URL下載MP3文件。我正在使用異步任務下載文件。出於測試目的,我已將文件保存在保管箱中。問題是,它不是下載完整的文件。實際文件大小爲5 MB。但是,它只下載29 KB的數據。當我檢查內容的長度時,它顯示-1。我不明白問題在哪裏。下面,我張貼我的代碼。Android:完整的文件沒有從網址下載

@Override 
    protected Void doInBackground(String... sUrl) 
    { 
     InputStream input = null; 
     OutputStream output = null; 
     try 
     { 
      URL link = new URL(sUrl[0]); 
      HttpURLConnection urlConnection = (HttpURLConnection)link.openConnection(); 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.setDoOutput(true); 
      urlConnection.connect(); 
      int fileLength = urlConnection.getContentLength(); 
      Log.v("Download file length", ""+fileLength); 
      input = urlConnection.getInputStream(); 
      int downloadedSize = 0; 
      output = new FileOutputStream(Environment.getExternalStorageDirectory() 
        .getAbsolutePath()+"/audiofolder/1.mp3.mp3"); 

      byte[] data = new byte[1024]; 
      int bufferLength = 0; 

      while (((bufferLength = input.read(data)) > 0)) 
      { 
       output.write(data, 0, bufferLength); 
       downloadedSize += bufferLength; 
       publishProgress((int)((downloadedSize/fileLength) * 100)); 
      }//while 
      output.flush(); 
      output.close(); 
      input.close(); 
     }//try 
     catch (MalformedURLException e) 
     { 
      e.printStackTrace(); 
     }//catch 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     }//catch 
     return null; 
    }//diInBackground 

回答

0

在我的應用程序中,下面的代碼完美地起作用。你可以試試這個。

@Override 
    protected Void doInBackground(String... aurl) { 

     try { 

      URL url = new URL(aurl[0]); 
      URLConnection conexion = url.openConnection(); 
      conexion.connect(); 

      File file = new File("mnt/sdcard/"); 
      file.mkdirs(); 
      File outputfile = new File(file, title + ".mp3"); 
      FileOutputStream fileOutput = new FileOutputStream(outputfile); 
      InputStream inputStream = conexion.getInputStream(); 
      int totalSize = conexion.getContentLength(); 
      int downloadedSize = 0; 
      byte[] buffer = new byte[1024]; 
      int bufferLength = 0; 
      while ((bufferLength = inputStream.read(buffer)) != -1) { 
       downloadedSize += bufferLength; 
       onProgressUpdate((int) ((downloadedSize * 100)/totalSize)); 
       fileOutput.write(buffer, 0, bufferLength); 
      } 
      fileOutput.close(); 
     } catch (Exception e) { 
      download = true; 
      e.printStackTrace(); 

     } 
     return null; 

    } 
+0

嘗試過,仍然是同樣的問題.... – Nitish

0

檢查您的鏈接。 當您看到內容長度= -1時,表示鏈接標題中沒有內容長度。它不會在您的下載過程中強制執行。 你只下載29KB,因爲它下載網站,.html不是文件mp3。 Yout可以將你的鏈接複製並粘貼到瀏覽器上進行檢查。