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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.