Thursday, March 24, 2011

Get file size in java

How to check the file size:
public static long getFileSize(String filename) {

File file = new File(filename);

if (!file.exists() || !file.isFile()) {
System.out.println("File doesn\'t exist");
return -1;
}

//Here we get the actual size
return file.length();
}

To get the file size in KB, just divide file.length() by 1024. i.e.


public static long getFileSizeInKB(String filename) {
File file = new File(filename);
if (!file.exists() || !file.isFile()) {
System.out.println("File doesn\'t exist");
return -1;
}
//Here we get the size in KB
return file.length()/1024;
}

No comments:

Post a Comment

Chitika