2015-06-19 81 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文本/纯“ 为每种文件.... 有人知道如何解决它? –

相关问题