【问题标题】:How to get the size of a file in MB (Megabytes)?如何以 MB(兆字节)为单位获取文件的大小?
【发布时间】:2012-02-17 20:55:12
【问题描述】:

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

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

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

【问题讨论】:

标签: java file url filesize


【解决方案1】:

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

您可以将转换合并为一个步骤,但我已尝试完整说明该过程。

【讨论】:

【解决方案2】:

试试下面的代码:

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

【讨论】:

    【解决方案3】:

    例子:

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

    【讨论】:

    • 做了很多不需要的东西,但我想新手更容易理解。
    【解决方案4】:

    最简单的方法是使用来自 Apache commons-io 的 FileUtils。(https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html)

    返回人类可读的文件大小,从 Bytes 到 Exabytes ,向下舍入到边界。

    File fileObj = new File(filePathString);
    String fileSizeReadable = FileUtils.byteCountToDisplaySize(fileObj.length());
    
    // output will be like 56 MB 
    

    【讨论】:

      【解决方案5】:

      file.length() 将返回以字节为单位的长度,然后将其除以 1048576,现在您得到了兆字节!

      【讨论】:

      • 感谢这个乘法,这让我免于书写 (1024*1024),节省了 4 次击键!! :D
      【解决方案6】:

      您可以使用File#length() 检索文件的长度,这将返回一个以字节为单位的值,因此您需要将其除以 1024*1024 以获得其以 mb 为单位的值。

      【讨论】:

        【解决方案7】:

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

        【讨论】:

          【解决方案8】:

          Kotlin 扩展解决方案

          将这些添加到某处,然后致电if (myFile.sizeInMb &gt; 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
          

          如果您希望更轻松地使用 String 或 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"
          

          【讨论】:

            【解决方案9】:
            public static long sizeOf(File file)
            

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

            【讨论】:

            【解决方案10】:

            您可以使用 substring 来获取等于 1 mb 的 String 的一部分:

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

            【讨论】:

              【解决方案11】:

              您可以在Java 中使用FileChannel

              FileChannel 有 size() 方法来确定文件的大小。

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

              或者您可以使用Apache Commons'FileUtils'sizeOf() 方法确定文件大小。如果您使用的是 maven,请将其添加到 pom.xml 文件中。

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

              试试下面的编码,

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

              这些方法将以字节为单位输出大小。因此,要获得 MB 大小,您需要将文件大小与 (1024*1024) 相除。

              现在您可以简单地使用if-else 条件,因为大小以MB 为单位。

              【讨论】:

                【解决方案12】:
                     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");             
                        }
                

                注意:1048576= (1024*1024)=1MB 输出:文件大小小于 1 mb

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2010-10-05
                  • 1970-01-01
                  • 2010-10-08
                  • 1970-01-01
                  • 2013-02-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多