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?
Asked
Active
Viewed 4,913 times
-2
-
3What have you tried? What do you want to do with it? Which libraries do you use? More info please. – Willem Van Onsem Mar 16 '14 at 05:19
3 Answers
3
Use the getContentLength
method of the URLConnection
which is obtained from URL#openConnection

MadProgrammer
- 343,457
- 22
- 230
- 366
-
Just remember, not all URLs will return a length, ts will come down to what the server returns – MadProgrammer Mar 17 '14 at 19:58
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!");
}

Chamara Maduranga
- 246
- 3
- 14
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