ตัวอย่าง
ในที่นี้เราจะคืนค่าขนาดของไฟล์ (C:\\users\\nopphanan7\\newfile.txt) ที่มีขนาด 21 bytes และ แสดงขนาดของไฟล์ในหน่วยอื่นๆด้วยครับ.
package demo.file;
import java.io.File;
public class FileSizeExample {
/**
* @param args
*/
public static void main(String[] args) {
File file = new File("C:\\users\\nopphanan7\\newfile.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!");
}
}
}
ผลลัพธ์ที่ได้คือ
bytes : 21.0 kilobytes : 0.0205078125 megabytes : 2.002716064453125E-5 gigabytes : 1.955777406692505E-8 terabytes : 1.9099388737231493E-11 petabytes : 1.865174681370263E-14 exabytes : 1.8214596497756474E-17 zettabytes : 1.7787691892340307E-20 yottabytes : 1.737079286361358E-23
0 comments:
Post a Comment