File in Java | File Class, Methods, Example

So far, we have used variables and arrays to store data inside Java programs. This approach creates two problems.

1. Data stored in a program is lost when the program is terminated. It means storage is temporary.

2. Large volumes of data are difficult to handle using variables and arrays.

To overcome these problems, we use secondary storage devices called hard disks to store large volumes of data.

The data is stored in the hard disk of a computer by using the concept of files. Data stored in files on a disk is called persistent data. Persistent means lasting.

Now let’s understand what is a file in Java and what a directory is.

What is File in Java?


A file is a collection of related records located in a specific area on the disk that stores user and system data. A record consists of many fields.

A field contains a group of Unicode characters composed of two bytes, each byte containing eight binary digits, 1 or 0.

In a system, files are organized using directories. A directory in Java is a file within a file system that contains several files and other directories.

A file system is a hierarchy of files and directories, starting from a root directory.

The root directory is the topmost directory in the file system, from which all files and directories derive. In Windows, it is represented by a drive name c:\, while on Linux it is represented by a single forward slash /.

In Java, files are used by several applications for storing and retrieving data. Storing and retrieving data using files is called file processing. Java supports the input and output of data through files.

Introducing File Class in Java


The java.io package provides a class known as File class that provides some methods to know the properties of files or directories.

The File class in Java provides several methods to perform operations, such as:

  • Creating a file.
  • Opening a file.
  • Deleting a file.
  • Closing a file.
  • Getting the file name.
  • Getting the size of a file.
  • Checking the existence of a file.
  • Renaming a file.
  • Testing whether a file is writable or not.
  • Testing whether a file is readable or not.

File class declaration


File class in Java is an abstract representation of file and directory pathnames. It extends Object class and implements Serializable and Comparable<File> interfaces.


The general syntax to declare file class in java is as follows:

public class File
  extends Object
     implements Serializable, Comparable<File>

File class was added in JDK 1.0 version. It is present in the java.io.File package.

Constructors of File Class


Java File class provides the following constructors to create File objects. They are as follows:

1. File(String pathName): This constructor creates a File object with the specified pathname. The pathname may be a file or a directory.
It converts the given pathname string into an abstract pathname.

2. File(String directoryPath, String filename): This constructor creates a new File instance from a directory with the specified directory path and filename.

3. File(File dirObject, String filename): This constructor creates a new File instance from a File object dirObject that specifies a directory and a file having the name filename.

4. File(URI uriObj): This constructor creates a new File instance from a URI object uri that specifies a file.


Note:

a) A path is a hierarchy of directories that locate a file or directory.

b) A pathname is a string representation of the path in which a platform-dependent separator character (\) appears between consecutive names.

c) A filename is a unique string of characters that locate a file on the disk. It may consist of two parts: primary name and an optional period with extension. For example, myfile.dat, student.txt, salary, etc.

d) Java File class does not contain any methods for reading and writing data in the file.

e) We must know the purpose of using a file. For example, we should know whether the file is built for reading only, or writing only, or both operations.

How to create File object in Java?


An object of a File class signifies the pathname of a particular file or directory on the file system. It is initialized as string that contains either an absolute or relative path to the file or directory within the file system.


a) The general syntax to create an object of File class by passing the filename or directory name to it is as follows:

File file = new File(filename); Here, the filename is a string of characters that identify a file on the disk.

For example:
// Creating a File object for file.
     File file = new File("myfile.txt"); // Assigning the filename to the file object.

// Creating a File object for directoty c:\book.
     File file = new File("c:\\book");

// Creating a File object of file c:\book\myfile.dat.
     File file = new File("c:\\book\\myfile.dat");

b) The general syntax to create an object of File class by passing pathname to it is as follows:

File file = new File(String pathName);

For example:
File file1 = new File("/"); // Passing directory path.
File file2 = new File("D:\\myfile.txt"); // Passing path of a file.

c) The general syntax to create an object of File class by passing pathname and filename to it as follows:

File file = new File(String pathName, String filename);

For example:
File file = new File("D:\\", "myfile.txt");

Before going to understand the methods of Java File class, first understand the basic concepts of abstract, absolute, relative, and canonical path names.

Go to this tutorial: Java Abstract, Absolute, Relative, and Canonical Pathnames

Methods of File Class in Java


File class in Java provides various useful methods for obtaining the properties of a file/directory and for renaming and deleting a file/directory within the file system.

The most commonly important methods of File class are as follows:

1. boolean exists(): Tests whether the file or directory represented by the File object exists. It returns true if exists.

2. boolean canExecute(): Tests whether the application can execute the file represented by File object. It returns true if executes.

3. boolean canRead(): This method returns true if the file represented by the File object exists and can be read.

4. boolean canWrite(): This method returns true if the file denoted by the File object exists and can be written.

5. boolean isAbsolute(): This method returns true if the File object is created using an absolute pathname. In other words, it checks whether this abstract pathname is absolute.


6. boolean isDirectory(): This method returns true if the File object represents a directory. That is, it checks whether the file represented by the abstract pathname is a directory.

7. boolean isFile(): This method returns true if the File object represents a file. That is, it checks whether the file represented by the abstract pathname is a normal file.

8. boolean isHidden(): This method returns true if the file represented in the File object is hidden. In other words, it checks whether the file named by this abstract pathname is a hidden file.

9. boolean createNewFile(): It basically constructs a new, empty file named by the abstract pathname if and only if a file with this name does not yet exist.

10. boolean delete(): This method deletes the file or directory represented by this File object. It returns true if the deletion succeeds.


11. File getAbsoluteFile(): This method returns the absolute form of the abstract pathname.

12. String getAbsolutePath(): This method returns the absolute pathname string of the abstract pathname.

13. File getCanonicalFile(): It returns the canonical form of the abstract pathname.

14. String getCanonicalPath(): It returns the canonical pathname string of this abstract pathname.

15. long getFreeSpace(): This method returns the number of unallocated bytes in the partition named by this abstract path name.


16. String getName(): This method returns the last name of the complete directory and file name represented by the File object. For example, new File(“c:\\book\\myfile.dat”).getName() returns myfile.dat.

17. String getPath(): This method returns the complete directory and file name represented by the File object. For example, new File(“c:\\book\\myfile.dat”).getPath() returns c:\book\myfile.dat.

18. String getParent(): This method returns the complete parent directory of the current directory or the file represented by the File object. For example, new File(“c:\\book\\myfile.dat”).getParent() returns c:\book.

19. long getTotalSpace(): This method returns the size of the partition defined by the abstract pathname.

20. long getUsableSpace(): It returns the number of bytes available to this virtual machine on the partition specified by the abstract pathname.


21. long lastModified(): This method returns the time that the file was last modified.

22. long length(): It returns the length (size) of the file or 0 if it does not exist or if it is a directory.

23. String[ ] list(): It returns an array of strings naming the files and directories in the directory represented by the File object.

24. File[ ] listFiles(): It returns the files under the directory for a directory File object.

25. static File[ ] listRoots(): It list the available file system roots.


26. boolean mkdir(): It creates a directory represented in this File object. It returns true if the directory is created successfully.

27. boolean mkdirs(): It is the same as mkdir() except that it creates a directory along with its parent directories if the parent directories do not exist.

28. boolean renameTo(File dest): The remaneTo() method is used to rename the file or directory represented by this File object to the specified name represented in dest. It returns true if the operation succeeds.

29. URI toURI(): This method creates a file: URI that represents the abstract pathname.

30. boolean setReadOnly(): The setReadOnly() method is used to mark the file or directory as read-only. This method was added in Java 1.2 version to File class.


31. boolean setExecutable(boolean executable): It is a convenient method to set the execute permission for the owner.

32. boolean setExecutable(boolean executable, boolean ownerOnly): It is used to set the execute permission for owner or everybody.

33. boolean setReadable(boolean readable): It is a convenient method to set the read permission for the owner.

34. boolean setReadable(boolean readable, boolean ownerOnly): It sets the read permission for the owner or everybody.

35. boolean setWritable(boolean writable): It is a convenient method to set the write permission for the owner.

36. boolean setWritable(boolean writable, boolean ownerOnly): It sets the write permission for the owner or everybody.

Thus, the File class in Java has provided a lot of methods that perform a variety of functions. But it does not provide methods for reading and writing the file contents.

File Class Example Programs


1. Let’s take an example program where we will check the existence of a file.

Program source code 1:

package javaProgram;
import java.io.File;
public class TestFiles {
public static void main(String[] args)
{
// Create an object of File class and pass the path of filename.
   File file = new File("D:\\myfile.txt");

// Check for the existence of file.
     if (file.exists()) {
	System.out.println("File already exists.");
     } else {
	 System.out.println("File does not exist.");
     }
 }
}
Output:
           File already exists. 

Note: Escape sequences (\\) must be included to separate the drive, folder, and file names in the path of file.


2. Let’s create a program where we will check the existence of a file and display the properties of that file. Look at the following source code.

Program source code 2:

package javaProgram;
import java.io.File;
import java.io.IOException;
public class TestFiles {
public static void main(String[] args) throws IOException
{
// Create an object of File class and pass path of filename.
   File file = new File("D:\\myfile.txt");
  
// Use File class methods on File object.
  System.out.println("Does myfile.txt exist? " + file.exists());
  System.out.println("File name: " +file.getName());
  System.out.println("File size in bytes: " +file.length());
  
  System.out.println("Path: " +file.getPath());
  System.out.println("Absolute path: " +file.getAbsolutePath());
  System.out.println("Canonical path: " +file.getCanonicalPath());
  
  System.out.println("Parent: " +file.getParent());
  System.out.println("Free space: " +file.getFreeSpace());
  
  System.out.println("Is myfile.txt a file? " + file.isFile());
  System.out.println("Is myfile.txt a directory? " + file.isDirectory());
  System.out.println("Is myfile.txt hidden? " + file.isHidden());
  
  System.out.println("Can myfile.txt be read? " + file.canRead());
  System.out.println("Can myfile.txt be written? " + file.canWrite());
  
  System.out.println("Last modified on " +new java.util.Date(file.lastModified()));
 }
}
Output:
       Does myfile.txt exist? true
       File name: myfile.txt
       File size in bytes: 28

       Path: D:\myfile.txt
       Absolute path: D:\myfile.txt
      Canonical path: D:\myfile.txt

      Parent: D:\
      Free space: 356475736064
      Is myfile.txt a file? true

      Is myfile.txt a directory? false
      Is myfile.txt hidden? false
      Can myfile.txt be read? true

      Can myfile.txt be written? true
      Last modified on Sun Jun 27 08:13:39 IST 2021

Explanation:

a) This program creates a File object and prints file properties.

b) The lastModified() method of Java File class returns the date and time when the file was last modified.

c) The Date class is used to print it on the console in a readable format.


Hope that this tutorial has covered almost all the important points related to File class in Java with example programs. I hope you will have understood the basic points of File class and its methods for performing different operations.

In the next tutorial, we will discuss different ways to create a text file in Java with example programs.
Thanks for reading!!!
Next ⇒ How to create a text file in Java⇐ Prev Next ⇒

Please share your love