Monday, March 25, 2013

The method code to download a file from a web url


private static void downloadStreamData(String url, String fileName) throws Exception {
        URL tU = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) tU.openConnection();
        String type = conn.getContentType();
        InputStream ins = conn.getInputStream();
        FileOutputStream fout = new FileOutputStream(new File(fileName));
        byte[] outputByte = new byte[4096];
        int bytesRead;
        int length = conn.getContentLength();
        int read = 0;
        while ((bytesRead = ins.read(outputByte, 0, 4096)) != -1) {
            read += bytesRead;
            System.out.println(read + " out of " + length);
            fout.write(outputByte, 0, bytesRead);
        }
        fout.flush();
        fout.close();
    }

No comments:

Post a Comment