如何获取文件大小(以MB为单位)?

95

我在服务器上有一个zip文件。

如何检查该文件大小是否大于27MB?

File file = new File("U:\intranet_root\intranet\R1112B2.zip");
if (file > 27) {
   //do something
}

在这里,您可以获得可读的文件大小格式... https://dev59.com/33A75IYBdhLWcg3wfpKr#5599842 - DocFoster
13个回答

195

使用File类的length()方法返回文件以字节为单位的大小。

// 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) {
  ...
}
您可以将转换步骤合并为一步,但我已经尝试充分说明过程。

1
我根据您的代码做了一个 jsfiddle,这样需要的人可以使用它来测试。 - yongchang

58

尝试使用以下代码:

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);

49

示例:

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


1
做了很多不必要的东西,但我想对于新手来说更容易理解。 - Buffalo

15

12

file.length()将返回文件大小(以字节为单位),您可以将其除以1048576,然后就得到了兆字节数!


10
谢谢这个乘法,它让我不用写 (1024*1024),节省了 4 个按键!:D - TapanHP
如何量化可读性损失? :P - Koenigsberg

4

自Java 7起,您可以使用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");
}

4
您可以使用File#length()获取文件的长度,它将返回以字节为单位的值,因此您需要将其除以1024 * 1024以获得其以MB为单位的值。

4
你可以像这样做:
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;
}

如何使用:

Integer filesize = new File("path").length();
getSizeLabel(filesize) // Output  16.02MB

file.length() 返回一个长整型值,而不是整型。 - KenobiBastila

2

Kotlin扩展解决方案

将以下代码添加到任意位置,然后调用if (myFile.sizeInMb > 27.0)或其他所需条件:

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

如果你希望更轻松地处理字符串或Uri,请尝试添加以下内容:

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

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

如果您想将这些值轻松地显示为字符串,这些是简单的包装器。可以自由定制默认显示的小数位数。

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"

这个解决方案在技术上是正确的,因为1 KB等于1024字节,但操作系统使用1000进制(包括Android)。如果您比较选择器中的文件大小和此逻辑,则可以看到这一点。虽然很愚蠢,但如果将其用于上传并满足服务器端要求,则是一个重要因素。 - DevinM

0

该方法返回文件(或目录)大小以字节为单位,而不是以兆字节为单位:http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#sizeOf(java.io.File)。为了获得以兆字节为单位的大小,您仍需要将其除以1024两次。 - Scadge

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接