download errors, can't open files

299 views Asked by At

My app has to connect to google drive. The connection works fine. I can see all the files in the drive. The download of the files works fine. Unfortunately when I try to open it the files are corrupted or I can't open them at all. Does anyone know a solution for this problem ??

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();
1

There are 1 answers

3
Trung NT Nguyen On

It's problem between your file length and byte buffer. For quickly, please change to and retry

byte[] buffer = new byte[1024];

or you could get the length of input stream then create buffer

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

Have fun!