How to get the size of a file in MB (Megabytes)?
Use the length()
method of the File
class to return the size of the file in bytes.
// Get file from file name
File file = new File("U:\intranet_root\intranet\R1112B2.zip");
// Get length of file in bytes
long fileSizeInBytes = file.length();
// Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
long fileSizeInKB = fileSizeInBytes / 1024;
// Convert the KB to MegaBytes (1 MB = 1024 KBytes)
long fileSizeInMB = fileSizeInKB / 1024;
if (fileSizeInMB > 27) {
...
}
You could combine the conversion into one step, but I've tried to fully illustrate the process.
Try following code:
File file = new File("infilename");
// Get the number of bytes in the file
long sizeInBytes = file.length();
//transform in MB
long sizeInMb = sizeInBytes / (1024 * 1024);
Example :
public static String getStringSizeLengthFile(long size) {
DecimalFormat df = new DecimalFormat("0.00");
float sizeKb = 1024.0f;
float sizeMb = sizeKb * sizeKb;
float sizeGb = sizeMb * sizeKb;
float sizeTerra = sizeGb * sizeKb;
if(size < sizeMb)
return df.format(size / sizeKb)+ " Kb";
else if(size < sizeGb)
return df.format(size / sizeMb) + " Mb";
else if(size < sizeTerra)
return df.format(size / sizeGb) + " Gb";
return "";
}