Table of contents
1.
Introduction
2.
Creation 
3.
Fields
4.
Constructors
5.
Methods
5.1.
canExecute()
5.2.
canRead()
5.3.
canWrite()
5.4.
compareTo(File pathname)
5.5.
createNewFile()
5.6.
createTempFile(String prefix, String suffix)
5.7.
delete()
5.8.
equals(Object obj)
5.9.
exists()
5.10.
getAbsolutePath()
5.11.
list()
5.12.
getFreeSpace()
5.13.
getName()
5.14.
getParent()
5.15.
getParentFile() 
5.16.
getPath()
5.17.
setReadOnly()
5.18.
isDirectory()
5.19.
isFile()
5.20.
isHidden()
5.21.
length()
5.22.
listFiles()
5.23.
mkdir()
5.24.
renameTo(File dest)
5.25.
setExecutable(boolean executable)
5.26.
setReadable(boolean readable)
5.27.
setReadable(boolean readable, boolean ownerOnly)
5.28.
setWritable(boolean writable)
5.29.
toString()
5.30.
toURI()
6.
Program
7.
Output
8.
FAQs
9.
Key Takeaways
Last Updated: Mar 27, 2024

File Class in Java

Author Pankhuri Goel
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The File class represents a file or directory pathname in Java. A simple string is insufficient to name files and directories because they have distinct formats on different platforms. Working with the pathname, deleting and renaming files, establishing new directories, showing the contents of a directory, and identifying various common properties of files and directories are all covered by the File class.

The File class represents a file or directory pathname in abstract form. There are two types of pathnames: absolute and relative. This class’s getParent() method can be used to find the parent of an abstract pathname.

Instances of the File class are immutable, which means that once generated, a File object’s abstract pathname will never change.

The File class is a part of the java.io package. Another package called java.nio can be used to work with files.

Creation 

First, we must build a File class object by supplying it with the filename or directory name. Certain operations on the actual file-system object, such as reading, writing, and executing, may be restricted by a file system. Access permissions are a term that refers to all of these constraints.

A File object is formed by supplying a string representing a file name, a String, or another File object as an argument.

Syntax: File fileName = new File(String pathName)

Example: File a = new File("/usr/local/sample");

This specifies an abstract file name for the sample file in the /usr/local directory. This is an absolute abstract file name.

Fields

static String pathSeparator:

It is a system-dependent path-separator character and is rendered as a string for convenience.

static char pathSeparatorChar:

It is a path-separator character that is system-dependent.

static String separator:

It is a string representation of the system-dependent default name-separator character.

static char separatorChar:

It is the default name-separator character that is system-dependent.

Constructors

File(File parent, String child):

Creates a new File instance given a child pathname string and a parent abstract pathname.

File(String pathname)

Converts the specified pathname string to an abstract pathname and creates a new File object.

File(String parent, String child)

Creates a new File instance from a parent pathname string and a child pathname string.

File(URI uri)

Converts the provided file: URI into an abstract pathname to create a new File instance.

Methods

Below mentioned are some of the methods available in the File class.

canExecute()

This function determines whether the application can execute the file specified by this abstract pathname.

Return type: boolean

canRead()

This function determines whether the application can read the file specified by this abstract pathname.

Return type: boolean

canWrite()

This function determines whether the application can edit the file identified by this abstract pathname.

Return type: boolean

compareTo(File pathname)

This method lexicographically compares two abstract pathnames.

Return type: int

createNewFile()

This method atomically creates a new, empty file named by the given abstract pathname.

Return type: boolean

createTempFile(String prefix, String suffix)

In the default temporary-file directory, this method creates an empty file.

Return type: File

delete()

It removes the file or directory that the abstract pathname refers to.

Return type: boolean

equals(Object obj)

In this method, the abstract pathname is compared to the specified object.

Return type: boolean

exists()

This function determines whether the file or directory specified by this abstract pathname exists.

Return type: boolean

getAbsolutePath()

The abstract pathname’s absolute pathname string is returned by this method.

Return type: String

list()

It returns a string array listing the directory’s files and folders.

Return type: String[]

getFreeSpace()

This function returns the number of bytes in the partition that are currently unallocated.

Return type: long

getName()

This function returns the name of the file or directory that this abstract pathname refers to.

Return type: String

getParent()

It returns the pathname string of the abstract pathname’s parent.

Return type: String

getParentFile() 

It returns the abstract pathname of the abstract pathname’s parent.

Return type: File

getPath()

This function converts an abstract pathname to a string pathname.

Return type: String

setReadOnly()

Only read activities are permitted on the specified file or directory.

Return type: boolean

isDirectory()

The file specified by this pathname is checked to see if it is a directory.

Return type: boolean

isFile()

This function determines whether the file represented by the abstract pathname is a regular file.

Return type: boolean

isHidden()

This function determines whether or not the file named by this abstract pathname is hidden.

Return type: boolean

length()

This function returns the length of the file represented by the abstract pathname.

Return type: long

listFiles()

It returns an array of abstract pathnames that denote the directory’s files.

Return type: File[]

mkdir()

In this method, the mentioned abstract pathname is used to create a directory.

Return type: boolean

renameTo(File dest)

The file specified by the abstract pathname is renamed.

Return type: boolean

setExecutable(boolean executable)

It is an easy way to change the owner’s execute authority.

Return type: boolean

setReadable(boolean readable)

It is a quick way to change the owner’s read permission.

Return type: boolean

setReadable(boolean readable, boolean ownerOnly)

It sets the read permission for the owner or everyone.

Return type: boolean

setWritable(boolean writable)

It is a quick way to change the owner’s write authorization.

Return type: boolean

toString()

This method returns the pathname string of the abstract pathname.

Return type: String

toURI()

This method creates a file URI for the given abstract pathname.

Return type: URI

Program

Now let's see a program depicting the working of some of these methods.

import java.io.File;
class fileProperty 
{
	public static void main(String[] args)
	{
		String fname = args[0];
		File f = new File(fname);

		// applying File class methods on File object
		System.out.println("File name: " + f.getName());
		System.out.println("Path: " + f.getPath());
		System.out.println("Absolute path: "+ f.getAbsolutePath());
		System.out.println("Parent: " + f.getParent());
		System.out.println("Exists: " + f.exists());
		
		if (f.exists())
		{
			System.out.println("It is writable: "+ f.canWrite());
			System.out.println("It is readable: " + f.canRead());
			System.out.println("It is a directory: "+ f.isDirectory());
			System.out.println("File size in bytes: "+ f.length());
		}
	}
}

Check out this article - File System Vs DBMS, and Duck Number in Java.

Output

Practice it on online java compiler for better understanding.

FAQs

  1. What is a class?
    A class is a prototype or blueprint defined by the user and used to create objects. It denotes the collection of properties or methods that all objects of the same type share. It is a logical entity and not a physical one. Fields, methods, constructors, blocks, nested classes, and interfaces can all be found in a Java class.
     
  2. Define a file.
    A file is an abstract path that does not exist in the physical world. The file’s underlying physical storage is only accessed when “used.” An abstract path is produced when a file is created indirectly. A file is one way of storing data according to specified requirements.
     
  3. What are exceptions?
    An exception is an unwanted or unexpected event that occurs during the execution of a programme and disrupts the program’s normal flow of instructions. Exceptions can be detected and handled by the programme. An object is created when a method throws an exception. This object is referred to as an exception object. It includes information regarding the exception, such as the error’s name and description and the program’s state at the time the error occurred.
     
  4. What are objects?
    The instance of a class is known as an object. It represents real-life entities and is a fundamental unit of Object-Oriented Programming. A typical Java application creates a large number of objects, which interact via invoking methods. State, behaviour, and identity are the three attributes of an object.

Key Takeaways

In this article, we learned about the File class in Java. We learned the various fields, constructors and methods associated with this class.

We hope this blog has helped you enhance your knowledge. If you want to learn more, check out our articles on File Input/Output - Coding Ninjas Coding Ninjas StudioFile Input Stream class - Coding Ninjas Coding Ninjas Studio and FilterInput/OutputStream - Coding Ninjas Coding Ninjas Studio. Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practise top problems, attempt mock tests, read interview experiences, and much more!

Happy Reading!

Live masterclass