Home »
Java programming language
Java File Class long length() method with Example
Java File Class long length() method: Here, we are going to learn about the long length() method of File class with its syntax and example.
Submitted by Preeti Jain, on July 14, 2019
File Class long length()
- This method is available in package java.io.File.length().
- This method is used to return the length of the file in bits which is represented by the filepath.
- This method returns the length of the file and in case if the file does not exist or empty file or exception occurs then it will return 0L.
Syntax:
long length(){
}
Parameter(s):
We don't pass any object as a parameter in the method of the File.
Return value:
The return type of this method is long, which is the length of the file in bits.
Java program to demonstrate example of length() method
// import the File class because we will use File class methods
import java.io.File;
// import the Exception class because it may raise an exception
// when working with files
import java.lang.Exception;
public class FileLength {
public static void main(String[] args) {
try {
// Specify the path of file and we use double slashes to
// escape '\' character sequence for windows otherwise
// it will be considerable as url.
File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjava.txt");
File file2 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\java.txt");
// By using length() method return the length of the file 1 in bits
// because here file exists.
System.out.println("The Length Of The File1 is " + " " + file1.length());
// By using length() method return 0L because here file does not exists.
System.out.println("The Length Of The File2 is " + " " + file2.length());
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output
D:\Programs>javac FileLength.java
D:\Programs>java FileLength
The Length Of The File1 is 45
The Length Of The File2 is 0