如何获得文件的大小以MB为单位?

问题描述 投票:50回答:9

我有一个服务器上的文件,这是一个zip文件。如何检查文件大小大于27 MB大?

File file = new File("U:\intranet_root\intranet\R1112B2.zip");
if (file > 27) {
   //do something
}
java file url filesize
9个回答
134
投票

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

// 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) {
  ...
}

你可以转换合并成一步,但我已经尽力充分说明这个过程。


41
投票

试试下面的代码:

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

32
投票

例如:

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


8
投票

file.length()将返回字节长度,那么你除以1048576,现在你已经有了兆!


7
投票

最简单的是通过使用从fileutils中的Apache公地-10。(https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html

返回人类可读的文件大小从字节到艾字节,四舍五入到边界。

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

// output will be like 56 MB 

3
投票

你可以检索与File#length()的文件,这将返回以字节为单位的长度值,所以你需要通过1024 * 1024分这个以获得其以MB为单位的值。


2
投票

由于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");
}

0
投票
public static long sizeOf(File file)

在API的更多信息:http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html


0
投票

您可以使用子获得字符串的一部分,它等于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);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.