-2

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?

kleopatra
  • 51,061
  • 28
  • 99
  • 211
bro1o1
  • 37
  • 2
  • 9

3 Answers3

3

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
2
    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!");
    }
0
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;
}
gordonpassy
  • 114
  • 1
  • 6