Java URL Download downloadFileAndRetry(final File file, final URL url, final int retry)

Here you can find the source of downloadFileAndRetry(final File file, final URL url, final int retry)

Description

download File And Retry

License

Open Source License

Declaration

private static void downloadFileAndRetry(final File file, final URL url, final int retry) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.*;
import java.net.*;

public class Main {
    private static void downloadFileAndRetry(final File file, final URL url, final int retry) throws IOException {
        final FileOutputStream fos = new FileOutputStream(file);
        try {//from w ww .java2  s .c  o m
            final byte[] buffer = new byte[8192];
            final InputStream stream = new BufferedInputStream(url.openConnection().getInputStream());
            try {
                int len;
                while ((len = stream.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
            } finally {
                stream.close();
            }
        } catch (IOException io) {
            if (retry > 0) {
                downloadFileAndRetry(file, url, retry - 1);
            } else
                throw io;
        } finally {
            fos.close();
        }
    }

    public static String read(final InputStream stream) throws IOException {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final byte[] buffer = new byte[8192];
        int len;
        while ((len = stream.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        return baos.toString("UTF-8");
    }
}

Related

  1. downloadFile(URL fileUrl, File out)
  2. downloadFile(URL theURL, String filePath)
  3. downloadFile(URL url, File toFile)
  4. downloadFile(URL url, String name)
  5. downloadFile(URL url, String path, String fileName)
  6. downloadFileFromInternet(String remoteUrl)
  7. downloadFileFromUrl(String urlPath, File file)
  8. downloadFileFromWeb(URL resourceURL, String fullPath)
  9. downloadFileFromWebserver(String fileUrl, String storageLocation)