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

13

97

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
}
Amersham answered 24/1, 2012 at 15:49 Comment(1)
Here you get readable file size formatting... https://mcmap.net/q/16973/-format-file-size-as-mb-gb-etc-duplicateNisen
N
198

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.

Nonie answered 24/1, 2012 at 16:0 Comment(1)
jsfiddle.net/darkkyoun/3g71k6ho/16 I did a fiddle base on your code, so whoever need it, can use the fiddle to test it outRhettrhetta
N
60

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);
Nakamura answered 24/1, 2012 at 15:51 Comment(0)
D
50

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 "";
}

Danforth answered 15/3, 2014 at 15:34 Comment(1)
Lots of unneeded stuff being done, but I guess it's easier for a newbie to understand.Passible
H
15

Easiest is by using FileUtils from Apache commons-io.( https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html )

Returns human readable file size from Bytes to Exabytes , rounding down to the boundary.

File fileObj = new File(filePathString);
String fileSizeReadable = FileUtils.byteCountToDisplaySize(fileObj.length());

// output will be like 56 MB 
Hugh answered 15/2, 2017 at 14:54 Comment(0)
E
12

file.length() will return you the length in bytes, then you divide that by 1048576, and now you've got megabytes!

Eagan answered 24/1, 2012 at 15:52 Comment(2)
Thanks for this multiplication, This saves me from writing (1024*1024), saved 4 keystrokes!! :DDeduct
How to quantify readability loss? :PTransposal
G
4

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.

Gregggreggory answered 24/1, 2012 at 15:53 Comment(0)
H
4

Since Java 7 you can use java.nio.file.Files.size(Path p).

Path path = Paths.get("C:\\1.txt");

long expectedSizeInMB = 27;
long expectedSizeInBytes = 1024 * 1024 * expectedSizeInMB;

long sizeInBytes = -1;
try {
    sizeInBytes = Files.size(path);
} catch (IOException e) {
    System.err.println("Cannot get the size - " + e);
    return;
}

if (sizeInBytes > expectedSizeInBytes) {
    System.out.println("Bigger than " + expectedSizeInMB + " MB");
} else {
    System.out.println("Not bigger than " + expectedSizeInMB + " MB");
}
Hamrah answered 10/6, 2016 at 8:29 Comment(0)
B
4

You can do something like this:

public static String getSizeLabel(Integer size) {

    String cnt_size = "0";
    double size_kb = size / 1024;
    double size_mb = size_kb / 1024;
    double size_gb = size_mb / 1024;

    if (Math.floor(size_gb) > 0) {
        try {
            String[] snplit = String.valueOf((size_gb)).split("\\.");
            cnt_size = snplit[0] + "." + snplit[1].substring(0, 2) + "GB";
        } catch (Exception e) {

            cnt_size = String.valueOf(Math.round(size_gb)) + "GB";
        }
    } else if (Math.floor(size_mb) > 0) {
        try {
            String[] snplit = String.valueOf((size_mb)).split("\\.");
            cnt_size = snplit[0] + "." + snplit[1].substring(0, 2) + "MB";

        } catch (Exception e) {

            cnt_size = String.valueOf(Math.round(size_mb)) + "MB";
        }
    } else {
        cnt_size = String.valueOf(Math.round(size_kb)) + "KB";
    }

    return cnt_size;
}

How To use:

Integer filesize = new File("path").length();
getSizeLabel(filesize) // Output  16.02MB
Bonanza answered 5/2, 2022 at 19:52 Comment(1)
file.length() returns a long value, not Integer.Alum
T
2

Kotlin Extension Solution

Add these somewhere, then call if (myFile.sizeInMb > 27.0) or whichever you need:

val File.size get() = if (!exists()) 0.0 else length().toDouble()
val File.sizeInKb get() = size / 1024
val File.sizeInMb get() = sizeInKb / 1024
val File.sizeInGb get() = sizeInMb / 1024
val File.sizeInTb get() = sizeInGb / 1024

If you'd like to make working with a String or Uri easier, try adding these:

fun Uri.asFile(): File = File(toString())

fun String?.asUri(): Uri? {
    try {
        return Uri.parse(this)
    } catch (e: Exception) {
    }
    return null
}

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"
Tomika answered 22/1, 2020 at 18:47 Comment(1)
This solution is technically correct as there are 1024 bytes in 1 KB however OS's use 1000 metric (including Android). You can see this if you compare the file size in the picker vs with this logic. Its stupid but an important factor if using this for uploading and meeting server sided requirements.Dugald
M
0
public static long sizeOf(File file)

More info on API : http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

Mudguard answered 3/11, 2013 at 6:10 Comment(1)
This method returns File (or directory) size in bytes, not in megabytes: commons.apache.org/proper/commons-io/apidocs/org/apache/commons/…. In order to get size in megabytes, you still need to divide by 1024 twice.Uppity
A
0

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);
        }
    }
Amphicoelous answered 18/4, 2017 at 6:38 Comment(0)
O
0

You can use FileChannel in Java.

FileChannel has the size() method to determine the size of the file.

    String fileName = "D://words.txt";

    Path filePath = Paths.get(fileName);

    FileChannel fileChannel = FileChannel.open(filePath);
    long fileSize = fileChannel.size();

    System.out.format("The size of the file: %d bytes", fileSize);

Or you can determine the file size using Apache Commons' FileUtils' sizeOf() method. If you are using maven, add this to pom.xml file.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

Try the following coding,

    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.

Obregon answered 11/11, 2019 at 7:55 Comment(0)
D
0
     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

Devoir answered 5/6, 2020 at 6:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.