Java URL Read getFileSize(String sURL)

Here you can find the source of getFileSize(String sURL)

Description

get File Size

License

Open Source License

Declaration

public static long getFileSize(String sURL) 

Method Source Code


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

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

import java.net.URL;

public class Main {
    public static long getFileSize(String sURL) {
        int nFileLength = -1;
        try {/*w  w  w  . j a v  a  2 s .  c o m*/
            URL url = new URL(sURL);
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            //   httpConnection.setRequestProperty("User-Agent", "Internet Explorer");
            int responseCode = httpConnection.getResponseCode();
            if (responseCode >= 400) {
                System.err.println("Error Code : " + responseCode);
                return -2; // -2 represent access is error
            }
            String sHeader;
            for (int i = 1;; i++) {
                sHeader = httpConnection.getHeaderFieldKey(i);
                if (sHeader != null) {
                    if (sHeader.equals("Content-Length")) {
                        nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));
                        break;
                    }
                } else
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(nFileLength);
        return nFileLength;
    }
}

Related

  1. getBodyResponse(HttpURLConnection con)
  2. getBytes(URL url)
  3. getBytes(URL url)
  4. getFileContentFromWeb(final URL srcUrl, final FileOutputStream destination)
  5. getFileSize(URL url)
  6. getFilesizeFromUrl(String urlString)
  7. getFromURL(String URL)
  8. getHTML(String pageURL, String encoding)