目录

如何获取文件的大小(以字节为单位)?(How to get a file's size in bytes?)

问题描述 (Problem Description)

如何获取以字节为单位的文件大小?

解决方案 (Solution)

此示例显示如何使用File类的file.exists()和file.length()方法获取文件的大小(以字节为单位)。

import java.io.File;
public class Main {
   public static long getFileSize(String filename) {
      File file = new File(filename);
      if (!file.exists() || !file.isFile()) {
         System.out.println("File doesn\'t exist");
         return -1;
      }
      return file.length();
   }
   public static void main(String[] args) {
      long size = getFileSize("c:/java.txt");
      System.out.println("Filesize in bytes: " + size);
   }
}

结果 (Result)

上面的代码示例将产生以下结果。要测试此示例,首先在“C”驱动器中创建一个文本文件“java.txt”。大小可能会根据文件的大小而有所不同。

File size in bytes: 480

以下是java中文件大小的另一个示例示例

import java.io.File;
public class FileSizeExample { 
   public static void main(String[] args) { 
      File file = new File("C:\\Users\\IoWiki7\\Desktop\\abc.png");
      if(file.exists()) { 
         double bytes = file.length();
         double kilobytes = (bytes/1024);
         double megabytes = (kilobytes/1024);
         double gigabytes = (megabytes/1024);
         double terabytes = (gigabytes/1024);
         double petabytes = (terabytes/1024);
         double exabytes = (petabytes/1024);
         double zettabytes = (exabytes/1024);
         double yottabytes = (zettabytes/1024);
         System.out.println("bytes : " + bytes);
         System.out.println("kilobytes : " + kilobytes);
         System.out.println("megabytes : " + megabytes);
         System.out.println("gigabytes : " + gigabytes);
         System.out.println("terabytes : " + terabytes);
         System.out.println("petabytes : " + petabytes);
         System.out.println("exabytes : " + exabytes);
         System.out.println("zettabytes : " + zettabytes);
         System.out.println("yottabytes : " + yottabytes);
      } else {
         System.out.println("File does not exists!");
      }
   }
}

上面的代码示例将产生以下结果。要测试此示例,首先在“C”驱动器中创建一个文本文件“java.txt”。大小可能会根据文件的大小而有所不同。

bytes : 6119.0
kilobytes : 5.9755859375
megabytes : 0.005835533142089844
gigabytes : 5.698762834072113E-6
terabytes : 5.565198080148548E-9
petabytes : 5.434763750145066E-12
exabytes : 5.307386474751041E-15
zettabytes : 5.182994604249064E-18
yottabytes : 5.061518168211976E-21
↑回到顶部↑
WIKI教程 @2018