Question

I am new to Java.. I was trying to get the file size from a URL but I failed can any one help me how to get the URL size in bytes?

Was it helpful?

Solution

Use the getContentLength method of the URLConnection which is obtained from URL#openConnection

OTHER TIPS

    File file =new File("xxxxx"); // file path

    if(file.exists()){
        double bytes = file.length();
        double kilobytes = (bytes / 1024);
        System.out.println("bytes : " + bytes);
        double megabytes = (kilobytes / 1024);
        System.out.println("kilobytes : " + kilobytes);
        double gigabytes = (megabytes / 1024);
        System.out.println("megabytes : " + megabytes);
        double terabytes = (gigabytes / 1024);
        System.out.println("gigabytes : " + gigabytes);
        double petabytes = (terabytes / 1024);
    }else{
         System.out.println("File does not exists!");
    }
public int getFileSizeInBytes(String path){
try {
        URL url=new URL(path);
        URLConnection urlConnection=url.openConnection();
        urlConnection.connect();
        int file_size=urlConnection.getContentLength();
        return  file_size;

    } catch (MalformedURLException e) {

    }catch (IOException e){

    }
    return -1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top