Java如何檔案大小?

2019-10-16 22:30:05

在java程式設計中,如何獲取檔案大小(以位元組為單位)?

此範例顯示如何使用File類的file.exists()file.length()方法獲取檔案的大小(以位元組為單位)。

package com.yiibai;

import java.io.File;

public class FileSize {
    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("F:/worksp/javaexamples/java_files/myfile.txt");
        System.out.println("Filesize in bytes: " + size);
    }
}

執行上述範例程式碼,將產生以下結果 -

Filesize in bytes: 466

注意:需要先建立F:/worksp/javaexamples/java_files/myfile.txt檔案。

範例-2

以下是java中獲取檔案大小的另一個範例:

package com.yiibai;

import java.io.File;

public class FileSize2 {
    public static void main(String[] args) {
        File file = new File("F:/worksp/javaexamples/java_files/while-loop.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!");
        }
    }
}

執行上述範例程式碼,將產生以下結果 -

bytes : 6026.0
kilobytes : 5.884765625
megabytes : 0.0057468414306640625
gigabytes : 5.6121498346328735E-6
terabytes : 5.4806150728836656E-9
petabytes : 5.352163157112955E-12
exabytes : 5.22672183311812E-15
zettabytes : 5.104220540154414E-18
yottabytes : 4.984590371244545E-21