Home > File > Lấy dung lượng của file trong Java

Lấy dung lượng của file trong Java

Trong Java, bạn có thể sử dụng phương thức File.length() để lấy về dung lượng của file theo đơn vị bytes.

package quyetdv.java.javaio.file;
import java.io.File;
public class FileSizeExample {
public static void main(String[] args) {
    File file = new File("test.txt");
    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!");
    }
 }
}
Advertisements
Categories: File
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: