Java Examples - Get File Size

Java 实例Java Examples

The following example demonstrates using the file.exists() and file.length() methods of the File class to get the file size, calculated in bytes (1KB = 1024 bytes):

Main.java file

import java.io.File; public class Main { public static long getFileSize(String filename) { File file = new File(filename); if (!file.exists() || !file.isFile()) { System.out.println("File does not exist"); return -1; } return file.length(); } public static void main(String[] args) { long size = getFileSize("c:/java.txt"); System.out.println("The size of java.txt file is:" + size); } }

The output of the above code is (the java.txt file is located on the C drive):

java.txt文件大小为: 480

Java 实例Java Examples

Other Extensions