2015-06-19 211 views
0

我的應用必須連接到谷歌驅動器。連接工作正常。 我可以看到驅動器中的所有文件。文件的下載工作正常。 不幸的是,當我試圖打開它的文件已損壞或我無法打開它們。有誰知道這個問題的解決方案?下載錯誤,無法打開文件

enter code here

URL url = new URL(fileURL); 

HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); 
int responseCode = httpConn.getResponseCode(); 

// always check HTTP response code first 
if (responseCode == HttpURLConnection.HTTP_OK) { 
    String fileName = ""; 
    String disposition = httpConn.getHeaderField("Content-Disposition"); 
    String contentType = httpConn.getContentType(); 
    int contentLength = httpConn.getContentLength(); 

    if (disposition != null) { 
     // extracts file name from header field 
     int index = disposition.indexOf("filename="); 
     if (index > 0) { 
      fileName = disposition.substring(index + 10, 
        disposition.length() - 1); 
     } 
    } else { 
     // extracts file name from URL 
     fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, 
       fileURL.length()); 
    } 
    System.out.println("Content-Type = " + contentType); 
    System.out.println("Content-Disposition = " + disposition); 
    System.out.println("Content-Length = " + contentLength); 
    System.out.println("fileName = " + fileName); 
    fileName = mr.getTitle(); 
    // opens input stream from the HTTP connection 
    // URLConnection connection = url.openConnection(); 
    String saveFilePath = saveDir + File.separator + fileName; 

    InputStream inputStream = httpConn.getInputStream(); 
    FileOutputStream outputStream = new 
    FileOutputStream(saveFilePath); 
    // opens an output stream to save into file 



    int bytesRead = 0; 
    // int read; 
    byte[] buffer = new byte[16384]; 
    // while ((bytesRead = inputStream.read(buffer)) > 0) { 
    // outputStream.write(buffer, 0, bytesRead); 
    // } 
    while ((bytesRead = inputStream.read(buffer)) != -1) { 
     outputStream.write(buffer, 0, bytesRead); 
    } 

    outputStream.flush(); 
    outputStream.close(); 
    inputStream.close(); 

    System.out.println("File downloaded"); 
} else { 
    System.out 
      .println("No file to download. Server replied HTTP code: " 
        + responseCode); 
} 
httpConn.disconnect(); 
+0

比較文件大小? – greenapps

+0

你是如何初始化'saveDir'的? – Blackbelt

+0

對不起,我是一個初學者,你的意思是? public static void downloadFile(元數據mr,字符串fileURL,字符串saveDir) throws IOException { –

回答

0

這是你的文件長度和字節緩存之間的問題。對於較快,請改變並重新

byte[] buffer = new byte[1024]; 

,或者你可以得到輸入流的長度,然後創建緩衝區

long streamLength = inputStream.available(); 
byte[] buffer = new byte[streamLength]; 

玩得開心!

+0

謝謝我現在嘗試 –

+0

no ...不起作用...當我嘗試打開文件時我不能,文件沒有有效的格式。順便謝謝 –

+0

好吧,我知道真正的問題,如果你想使用連接到你的谷歌驅動器配置文件和下載文件的應用程序,你必須先在驅動器上公開設置文件。 否則當你下載你不能打開存儲的文件,因爲有一個安全塊從谷歌和日誌貓你有 「android content-disposition null」 「android content-lenght -1」 「android content-Type文本/純「 爲每種文件.... 有人知道如何解決它? –

相關問題