2014-06-10 35 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