Example usage for java.net URLConnection getContentLength

List of usage examples for java.net URLConnection getContentLength

Introduction

In this page you can find the example usage for java.net URLConnection getContentLength.

Prototype

public int getContentLength() 

Source Link

Document

Returns the value of the content-length header field.

Usage

From source file:org.jab.docsearch.DocSearch.java

private boolean downloadURLToFile(String urlString, String fileToSaveAs) {
    int numBytes = 0;
    int curI = 0;
    FileOutputStream dos = null;//from w ww .j  av a 2 s  .  c  o  m
    InputStream urlStream = null;
    int lastPercent = 0;
    int curPercent = 0;
    try {
        URL url = new URL(urlString);
        File saveFile = new File(fileToSaveAs);
        dos = new FileOutputStream(saveFile);
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.connect();
        urlStream = conn.getInputStream();
        int totalSize = conn.getContentLength();
        while (curI != -1) {
            curI = urlStream.read();
            byte curBint = (byte) curI;
            if (curI == -1) {
                break;
            }
            dos.write(curBint);
            numBytes++;
            if (totalSize > 0) {
                curPercent = (numBytes * 100) / totalSize;
                if (curPercent != lastPercent) {
                    setStatus(curPercent + " " + I18n.getString("percent_downloaded") + " "
                            + I18n.getString("of_file") + " " + urlString + " " + I18n.getString("total_bytes")
                            + " " + totalSize);
                    lastPercent = curPercent;
                }
            }
            // end if total size not zero
        }
        urlStream.close();
        dos.close();
    } catch (IOException ioe) {
        logger.fatal("downloadURLToFile() failed", ioe);
        showMessage(I18n.getString("error_download_file"), ioe.toString());
        return false;
    } finally {
        IOUtils.closeQuietly(dos);
        IOUtils.closeQuietly(urlStream);
    }

    return true;
}