Java.io.File.length() Method

Advertisements


Description

The java.io.File.length() returns the length of the file defined by this abstract pathname. The return value is unspecified if this pathname defines a directory.

Declaration

Following is the declaration for java.io.File.length() method:

public long length()

Parameters

  • NA

Return Value

The method returns length, in bytes, of the file denoted by this abstract pathname.

Exception

  • SecurityException -- If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the file

Example

The following example shows the usage of java.io.File.length() method.

package com.tutorialspoint;

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
      String path;
      long len;
      boolean bool = false;
      
      try{      
         // create new file
         f = new File("c:/test.txt");
         
         // true if the file path is a file, else false
         bool = f.exists();
         
         // if path exists
         if(bool)
         {
            // returns the length in bytes
            len = f.length();
                                 
            // path
            path = f.getPath();
            
            // print
            System.out.print(path+" file length: "+len);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program:

ABCDE  

Let us compile and run the above program, this will produce the following result:

c:\test.txt file length: 5



Advertisements
Advertisements