The perfect place for easy learning...

Java Programming

×

Topics List


File class in Java





The File is a built-in class in Java. In java, the File class has been defined in the java.io package. The File class represents a reference to a file or directory. The File class has various methods to perform operations like creating a file or directory, reading from a file, updating file content, and deleting a file or directory.

The File class in java has the following constructors.

S.No. Constructor with Description
1 File(String pathname)

It creates a new File instance by converting the givenpathname string into an abstract pathname. If the given string isthe empty string, then the result is the empty abstract pathname.

2 File(String parent, String child)

It Creates a new File instance from a parent abstractpathname and a child pathname string. If parent is null then the new File instance is created as if by invoking thesingle-argument File constructor on the given child pathname string.

3 File(File parent, String child)

It creates a new File instance from a parent abstractpathname and a child pathname string. If parent is null then the new File instance is created as if by invoking thesingle-argument File constructor on the given child pathname string.

4 File(URI uri)

It creates a new File instance by converting the given file: URI into an abstract pathname.

The File class in java has the following methods.

S.No. Methods with Description
1 String getName()

It returns the name of the file or directory that referenced by the current File object.

2 String getParent()

It returns the pathname of the pathname's parent, or null if the pathname does not name a parent directory.

3 String getPath()

It returns the path of curent File.

4 File getParentFile()

It returns the path of the current file's parent; or null if it does not exist.

5 String getAbsolutePath()

It returns the current file or directory path from the root.

6 boolean isAbsolute()

It returns true if the current file is absolute, false otherwise.

7 boolean isDirectory()

It returns true, if the current file is a directory; otherwise returns false.

8 boolean isFile()

It returns true, if the current file is a file; otherwise returns false.

9 boolean exists()

It returns true if the current file or directory exist; otherwise returns false.

10 boolean canRead()

It returns true if and only if the file specified exists and can be read by the application; false otherwise.

11 boolean canWrite()

It returns true if and only if the file specified exists and the application is allowed to write to the file; false otherwise.

12 long length()

It returns the length of the current file.

13 long lastModified()

It returns the time that specifies the file was last modified.

14 boolean createNewFile()

It returns true if the named file does not exist and was successfully created; false if the named file already exists.

15 boolean delete()

It deletes the file or directory. And returns true if and only if the file or directory is successfully deleted; false otherwise.

16 void deleteOnExit()

It sends a requests that the file or directory needs be deleted when the virtual machine terminates.

17 boolean mkdir()

It returns true if and only if the directory was created; false otherwise.

18 boolean mkdirs()

It returns true if and only if the directory was created, along with all necessary parent directories; false otherwise.

19 boolean renameTo(File dest)

It renames the current file. And returns true if and only if the renaming succeeded; false otherwise.

20 boolean setLastModified(long time)

It sets the last-modified time of the file or directory. And returns true if and only if the operation succeeded; false otherwise.

21 boolean setReadOnly()

It sets the file permission to only read operations; Returns true if and only if the operation succeeded; false otherwise.

22 String[] list()

It returns an array of strings containing names of all the files and directories in the current directory.

23 String[] list(FilenameFilter filter)

It returns an array of strings containing names of all the files and directories in the current directory that satisfy the specified filter.

24 File[] listFiles()

It returns an array of file references containing names of all the files and directories in the current directory.

25 File[] listFiles(FileFilter filter)

It returns an array of file references containing names of all the files and directories in the current directory that satisfy the specified filter.

26 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 this abstract pathname.

27 int compareTo(File pathname)

It Compares two abstract pathnames lexicographically. It returns zero if the argument is equal to this abstract pathname, a value less than zero 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.

28 int compareTo(File pathname)

Compares this abstract pathname to another object. Returns zero if the argument is equal to this abstract pathname, a value less than zero 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.

Let's look at the following code to illustrate file operations.

Example
import java.io.*;
public class FileClassTest {
	
	public static void main(String args[]) {
		File f = new File("C:\\Raja\\datFile.txt");
		
		System.out.println("Executable File : " + f.canExecute());
		System.out.println("Name of the file : " + f.getName());
		System.out.println("Path of the file : " + f.getAbsolutePath());
		System.out.println("Parent name :  " + f.getParent());
		System.out.println("Write mode :  " + f.canWrite());
		System.out.println("Read mode :  " + f.canRead());
		System.out.println("Existance :  " + f.exists());
		System.out.println("Last Modified :  " + f.lastModified());
		System.out.println("Length :  " + f.length());
		//f.createNewFile()
		//f.delete();
		//f.setReadOnly()
	}

}

When we run the above program, it produce the following output.

File class in java

Let's look at the following java code to list all the files in a directory including the files present in all its subdirectories.

Example
import java.util.Scanner;
import java.io.*;

public class ListingFiles {
	public static void main(String[] args) {

		String path = null;
		Scanner read = new Scanner(System.in);
		System.out.print("Enter the root directory name: ");
		path = read.next() + ":\\";
		File f_ref = new File(path);
		if (!f_ref.exists()) {
			printLine();
			System.out.println("Root directory does not exists!");
			printLine();
		} else {
			String ch = "y";
			while (ch.equalsIgnoreCase("y")) {
				printFiles(path);
				System.out.print("Do you want to open any sub-directory (Y/N):  ");
				ch = read.next().toLowerCase();
				if (ch.equalsIgnoreCase("y")) {
					System.out.print("Enter the sub-directory name: ");
					path = path + "\\\\" + read.next();
					File f_ref_2 = new File(path);
					if (!f_ref_2.exists()) {
						printLine();
						System.out.println("The sub-directory does not exists!");
						printLine();
						int lastIndex = path.lastIndexOf("\\");
						path = path.substring(0, lastIndex);
					}
				}
			}
		}
		System.out.println("***** Program Closed *****");
	}

	public static void printFiles(String path) {
		System.out.println("Current Location: " + path);
		File f_ref = new File(path);
		File[] filesList = f_ref.listFiles();
		for (File file : filesList) {
			if (file.isFile())
				System.out.println("- " + file.getName());
			else
				System.out.println("> " + file.getName());
		}
	}

	public static void printLine() {
		System.out.println("----------------------------------------");
	}
}

When we run the above program, it produce the following output.

File class in java