2014-06-10 66 views
0

我試圖下載並將文件保存到SD卡。文件的URL如下讀取輸入流並使用DownloadManager下載

http://test.com/net/Webexecute.aspx?fileId=120 

此網址提供了一個數據流。我有以下選項來讀取輸入流。

  • 使用的通用輸入和輸出流(用於連接沒有處理失敗 旁白)

  • 下載管理

  • 使用HttpURLConnection的(可能超時的機會)

我有使用選項a完成下載。但是沒有連接失敗的處理程序。所以我決定選擇b

DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); 
Request request = new Request(Uri.parse("http://test.com/net/Webexecute.aspx?fileId="+ fileId)); 
request.setMimeType("application/pdf"); 
request.setDescription("fileDownload"); 
request.setTitle(fileName); 
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
dm.enqueue(request); 

它正在下載文件。但是,該文件似乎已損壞。

在進行研究時,我從來沒有發現使用DownloadManager來獲取輸入流並將其保存到文件中。有什麼我缺乏?

回答

0

請更改您的代碼以下載文件。

保護無效downLoadFile(字符串fileURL) {

int count; 
    try 
    { 

     URL url = new URL(fileURL); 
     URLConnection conexion = url.openConnection(); 
     conexion.connect(); 
     int lenghtOfFile = conexion.getContentLength(); 
     InputStream is = url.openStream(); 

     File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Download"); 
     if (!testDirectory.exists()) 
     { 
      testDirectory.mkdir(); 
     } 

     FileOutputStream fos = new FileOutputStream(testDirectory + "/filename.txt"); 


     byte data[] = new byte[1024]; 
     long total = 0; 
     int progress = 0; 
     while ((count = is.read(data)) != -1) 
     { 
      total += count; 
      int progress_temp = (int) total * 100/lenghtOfFile; 

      fos.write(data, 0, count); 

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

     readStringFromFile(testDirectory); 

    } 
    catch (Exception e) 
    { 
     Log.e("ERROR DOWNLOADING", "Unable to download" + e.getMessage()); 
     e.printStackTrace(); 
    } 
    return null; 

下面方法被用來從文件中讀取字符串。

public String readStringFromFile(File file){ 
     String response=""; 
     try 
     { 
      FileInputStream fileInputStream= new FileInputStream(file+"/filename.txt"); 
      StringBuilder builder = new StringBuilder(); 
      int ch; 
      while((ch = fileInputStream.read()) != -1){ 
       builder.append((char)ch); 
      } 
      response = builder.toString(); 

     } 
     catch (FileNotFoundException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     catch (IOException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return response; 
    } 

讓我知道你仍然面臨的任何問題..

感謝

+0

感謝您的輸入!是的,這會起作用。我有工作流閱讀器。但是,這種方法沒有連接失敗的處理程序。 – Renjith