在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