Lấy kích thước file trong Java

Trong Java, bạn có thể sử dụng phương thức File.length() để lấy kích thước file theo byte.

Thí dụ

Lấy kích thước của file hình ảnh (E:\project\huongdanjava\javaio\javaio.png) có 10KB

package com.itphutran.file;

import java.io.File;

public class FileSizeExample
{
 public static void main(String[] args)
 {
 File file =new File("E:\\project\\huongdanjava\\javaio\\javaio.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!");
 }

 }
}

Kết quả:

bytes : 9878.0
kilobytes : 9.646484375
megabytes : 0.009420394897460938
gigabytes : 9.199604392051697E-6
terabytes : 8.983988664112985E-9
petabytes : 8.773426429797837E-12
exabytes : 8.56779924784945E-15
zettabytes : 8.366991452977979E-18
yottabytes : 8.170890090798807E-21

 

0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Phản hồi nội tuyến
Xem tất cả bình luận
x