Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the size of a file in MB (Megabytes)?

I have a zip file on a server.

How can I check if the file size is larger than 27 MB?

File file = new File("U:\intranet_root\intranet\R1112B2.zip"); if (file > 27) {    //do something } 
like image 571
itro Avatar asked Jan 24 '12 15:01

itro


People also ask

How do you find the file size?

Click the file or folder. Press Command + I on your keyboard. A window opens and shows the size of the file or folder.

How do I convert MB to size?

To convert file size to MB in JavaScript, we can divide the number of bytes by 1024 raise to the power of 2. to define the bytesToMegaBytes function that divide bytes by 1024 ** 2 .

How do I find the file size in KB?

Step 2: Multiply total number of pixels by the bit depth of the detector (16 bit, 14 bit etc.) to get the total number of bits of data. Step 3: Dividing the total number of bits by 8 equals the file size in bytes. Step 4: Divide the number of bytes by 1024 to get the file size in kilobytes.


2 Answers

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.

like image 199
Marcus Adams Avatar answered Sep 22 '22 17:09

Marcus Adams


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); 
like image 29
endian Avatar answered Sep 20 '22 17:09

endian