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);
You can retrieve the length of the file with File#length(), which will return a value in bytes, so you need to divide this by 1024*1024 to get its value in mb.
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.
You can use substring to get portio of String which is equal to 1 mb:
public static void main(String[] args) {
// Get length of String in bytes
String string = "long string";
long sizeInBytes = string.getBytes().length;
int oneMb=1024*1024;
if (sizeInBytes>oneMb) {
String string1Mb=string.substring(0, oneMb);
}
}
String fileName = "D://words.txt";
File f = new File(fileName);
long fileSize = FileUtils.sizeOf(f);
System.out.format("The size of the file: %d bytes", fileSize);
These methods will output the size in Bytes. So to get the MB size, you need to divide the file size from (1024*1024).
Now you can simply use the if-else conditions since the size is captured in MB.
If you'd like to easily display the values as a string, these are simple wrappers. Feel free to customize the default decimals displayed
fun File.sizeStr(): String = size.toString()
fun File.sizeStrInKb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInKb)
fun File.sizeStrInMb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInMb)
fun File.sizeStrInGb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInGb)
fun File.sizeStrWithBytes(): String = sizeStr() + "b"
fun File.sizeStrWithKb(decimals: Int = 0): String = sizeStrInKb(decimals) + "Kb"
fun File.sizeStrWithMb(decimals: Int = 0): String = sizeStrInMb(decimals) + "Mb"
fun File.sizeStrWithGb(decimals: Int = 0): String = sizeStrInGb(decimals) + "Gb"
String FILE_NAME = "C:\\Ajay\\TEST\\data_996KB.json";
File file = new File(FILE_NAME);
if((file.length()) <= (1048576)) {
System.out.println("file size is less than 1 mb");
}else {
System.out.println("file size is More than 1 mb");
}
Note: 1048576= (1024*1024)=1MB
output : file size is less than 1 mb