Java 实例 - 获取文件大小


以下实例演示了使用 File 类的 file.exists() 和 file.length() 方法来获取文件大小,以字节计算(1KB=1024字节 ):

  1. /*
  2. author by shouce.ren
  3. Main.java
  4. */
  5.  
  6. import java.io.File;
  7.  
  8. public class Main {
  9. public static long getFileSize(String filename) {
  10. File file = new File(filename);
  11. if (!file.exists() || !file.isFile()) {
  12. System.out.println("文件不存在");
  13. return -1;
  14. }
  15. return file.length();
  16. }
  17. public static void main(String[] args) {
  18. long size = getFileSize("c:/java.txt");
  19. System.out.println("java.txt文件大小为: " + size);
  20. }
  21. }

以上代码运行输出结果为(java.txt 文件位于 C 盘):

  1. java.txt文件大小为: 480