Home »
Java Programs »
Java File Handling Programs
Java program to get file size and file path
This program will print the exact (absolute) path of the file and file length i.e. file size in bytes, to get the file path we will use the File.getAbsolutePath() method and to get file length (size) we will use File.length() Method.
File.getAbsolutePath() - Method return absolute path of the file, this is the method of File class.
File.length() - Method returns the file size (length) in the bytes, this is also method of File class.
Get File Length (Size) and File Path in Java
// Java program to get file size
// and file path
import java.io.File;
public class GetFilePathAndSize {
public static void main(String args[]) {
final String fileName = "file1.txt";
try {
//File Object
File objFile = new File(fileName);
//getting file path
System.out.println("File path is: " + objFile.getAbsolutePath());
//getting filesize
System.out.println("File size is: " + objFile.length() + " bytes.");
} catch (Exception Ex) {
System.out.println("Exception: " + Ex.toString());
}
}
}
Output
File path is: d:/programs/file1.txt
File size is: 40 bytes.
Java File Handling Programs »