Core Java

Java File Class Example

1. Introduction

In Java, File io is a class residing in java.io package, which provides an abstract representation of file and directory pathname. The pathname can be of either an absolute or a relative manner. The File io class in Java provides functionalities such as creating, deleting, renaming, searching and identifying common attributes in files and directories, listing the contents of a directory and much more.

Java File Class

In the following sections, we will discuss the different types in which the File io java objects can be created and various methods that are used for file and directory operations. We will also look at the detailed implementation via examples to perform several operations on files.

2. File Constructors

The File class object depicts the actual file/directory stored on the disk. The File class instances are immutable, i.e., once the instance is initialized with the abstract pathname, then it remains the same and cannot be modified in the whole program.

There are various types of constructor call that can be made to create the File object. They are explained as follows:

  • File(File parent, String child): It creates a new File instance from a parent abstract pathname and a child pathname string.
  • File(String pathname): It creates a new File instance by converting the given pathname string into an abstract pathname.
  • File(String parent, String child): It creates a new File instance from a parent pathname string and a child pathname string.
  • File(URI uri): It creates a new File instance by converting the given file: URI into an abstract pathname.

3. Java File Methods

There are several methods in File class that are used for different file manipulation operations. Few of them are explained as follows:

  • boolean createNewFile(): It creates a new, empty file named by this abstract pathname automatically, if and only if no file with the same name exists.
  • static File createTempFile(String prefix, String suffix): It creates an empty file in the default temporary-file directory with its name generated by the given prefix and suffix.
  • boolean delete(): It deletes the file or directory represented by the object’s abstract pathname.
  • String getName(): It returns the name of the file or directory denoted by the object’s abstract pathname.
  • String getParent(): It returns the parent’s pathname string of the object’s abstract pathname or null if the pathname does not name a parent directory.
  • String getPath(): It returns the object’s abstract pathname into a pathname string.
  • String getAbsolutePath(): It returns the absolute pathname string of the object’s abstract pathname.
  • File getParentFile(): It returns the parent’s abstract pathname of the object’s abstract pathname.
  • boolean isFile(): It returns True if the file denoted by the abstract pathname is a normal file, and False if it is not a normal file.
  • boolean isDirectory(): It returns True if the file denoted by the abstract pathname is a directory, and False if it is not a directory.
  • boolean isHidden(): It returns True if the file denoted by the abstract pathname is a hidden file, and False if it is not a hidden file.
  • boolean canRead(): It returns True if the application can read the file denoted by the abstract pathname, and returns False otherwise.
  • boolean canWrite(): It returns True if the application can modify the file denoted by the abstract pathname, and returns False otherwise.
  • boolean canExecute(): It returns True if the application can execute the file denoted by the abstract pathname, and returns False otherwise.
  • boolean equals(Object obj): It returns True if and only if the argument is not null and is an abstract pathname that denotes the same file or directory as the object’s abstract pathname, and returns False otherwise.
  • int compareTo(File pathname): It compares two abstract pathnames lexicographically. It returns 0 if the argument is equal to the object’s abstract pathname, a value less than 0 if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.

4. Java File Class Example

This section provides an example of implementing the File class, by creating a file and displaying its various properties, with the help of the methods called by the File class object. The code is written in Nodepad++ and executed via Command Prompt. Java 8 IDE is installed and used for implementation. The code is the same and can run on any Java’s IDE like Eclipse, NetBeans, Spring, etc. The example is shown in the below code snippet.

FileOperations.java

/*Program to create a new file and displaying various properties of the file.*/
import java.io.*;

public class FileOperations {
  //Main function
  public static void main(String[] args) {
    try {
	  File file = new File("FileExample.txt");
	  
	  //Creating a new file if it doesn't already exist.
	  if(file.createNewFile())
		  System.out.println("A new file is successfully created.");
	  else
		  System.out.println("File already exists.");
	  
	  //Displaying various properties of file using File class methods, called with its object named 'file'.
	  System.out.println("File name : " + file.getName());
	  System.out.println("Parent name : " + file.getParent());
	  System.out.println("File size (bytes) : " + file.length());
	  System.out.println("Path : " + file.getPath());
	  System.out.println("Absolute path : " + file.getAbsolutePath());
	  System.out.println("Is file readable : " + file.canRead());
	  System.out.println("Is file writeable : " + file.canWrite());
	  System.out.println("Is file executable : " + file.canExecute());
	  System.out.println("Is file a directory : " + file.isDirectory());	  
	} 
	catch(IOException e) {
		System.out.println("An IOException ocuured : " + e);
	}
  }
}

The above program demonstrates the implementation of various file operations via File class object, named file. First, the method, createNewFile() checks if the file, FileExample.txt already exists in the current directory or it is newly created. The methods getName() and getParent() returns the names of the file and parent of the file respectively. The size of the file is returned in bytes with the length() method. The relative and absolute path of the file is returned by getPath() and getAbsolutePath() methods of the File class. The methods canRead(), canWrite() and canExecute() returns the boolean value of True or False depicting if the file is readable, writeable and executable respectively. The isDirectory() method of File class returns True if the file is a directory, else returns False.

Now, set the appropriate path on the command prompt (cmd) where the program file FileOperations.java is stored. To compile and execute the program write the following commands on cmd:

>javac FileOperations.java
>java FileOperations

The following is the output of FileOperations.java program that occurs on the successful execution of the program:

Output

A new file is successfully created.
File name : FileExample.txt
Parent name : null
File size (bytes) : 3
Path : FileExample.txt
Absolute path : D:\Dhruvi\Java Code Geeks\FileExample.txt
Is file readable : true
Is file writeable : true
Is file executable : true
Is file a directory : false

5. Download Source Code

This was an example to demonstrate the usage of various methods of the File class via Java Program.

Download
You can download the full source code of this example here: Java File Class Example

Dhruvi Goyal

Dhruvi Goyal is a graduate and University Gold Medalist in Bachelor of Computer Application from GGS Indraprastha University. She is currently pursuing M.Sc. Applied Operational Research from University of Delhi. She is a coder and a data science enthusiast. She has undertaken various projects and research work in the field of Computer Science, Data Science and Optimization. She is co-author of a book entitled "Data Structure Using C" and has published research papers in reputed International Journals and Conferences. She was also a member of Software Development Cell at Maharaja Surajmal Institute.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button