Galion
Galion

Reputation: 33

Android download file get corrupted

    btnShowProgress.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                download();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}
public void download() throws IOException {
    URL url = new URL("URL");
        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();
        String PATH = Environment.getExternalStorageDirectory()
                        + "/download/";
        File file = new File(PATH);
        file.mkdirs();
        String fileName = "Dragonfly";
        File outputFile = new File(file, fileName);
        FileOutputStream fos = new FileOutputStream(outputFile);
        InputStream is = c.getInputStream();
        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = is.read(buffer)) > 0) {
            fos.write(buffer, 0, len1);
        }
        fos.flush();
        fos.close();
        is.close();

I use the code to download a file from own server, but file always get downloaded with 9,3KB (even if file have lower size, like 2KB) and cant open the file.

Upvotes: 2

Views: 2667

Answers (1)

Ganster41
Ganster41

Reputation: 486

This is my app updated downloader code. It works for me:

URL url = new URL(mUpdateUrl);
Log.d(LOG_TAG, "Connect to: " + mUpdateUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

int response = connection.getResponseCode();

if(response == 200)
{
    BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
    FileOutputStream fs = new FileOutputStream(filename);
    BufferedOutputStream out = new BufferedOutputStream(fs);
    byte [] buffer = new byte[16384];

    int len = 0;
    while ((len = in.read(buffer, 0, 16384)) != -1)
        out.write(buffer, 0, len);

    out.flush();
    in.close();
    out.close();
} else {
    Log.d(LOG_TAG, "Server return code: " + response + ", url: " + url);
    connection.disconnect();
    return null;
}

connection.disconnect();
return filename;

Upvotes: 4

Related Questions