File Objects in Java


The File object represents the actual file/directory on the disk. Here are the list of constructors to create File Object in Java −

Sr.No.Method & Description
1File(File parent, String child)This constructor creates a new File instance from a parent abstract pathname and a child pathname string.
2File(String pathname)This constructor creates a new File instance by converting the given pathname string into an abstract pathname.
3File(String parent, String child)This constructor creates a new File instance from a parent pathname string and a child pathname string.
4File(URI uri)This constructor creates a new File instance by converting the given file: URI into an abstract pathname.

Assuming an object is present in the given location, the first argument to the command line will be considered as the path and the below code will be executed −

Example

import java.io.File;
public class Demo{
   public static void main(String[] args){
      String file_name =args[0];
      File my_file = new File(file_name);
      System.out.println("File name is :"+my_file.getName());
      System.out.println("The path to the file is: "+my_file.getPath());
      System.out.println("The absolute path to the file is:" +my_file.getAbsolutePath());
      System.out.println("The parent directory is :"+my_file.getParent());
      if(my_file.exists()){
         System.out.println("Is the file readable"+my_file.canRead());
         System.out.println("The size of the file in bytes is "+my_file.length());
      }
   }
}

Output

The details about the file will be displayed here.

A class named Demo contains the main function, and a string is defined, that holds the first argument passed in the command line. The details of the file are printed on the screen, this includes name of the file, file path, the absolute path of the file, and the parent directory of the file.

Updated on: 17-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements