Java File Class - java.io.File With Examples

Java File class is at the center of Java IO operations.

Java File Class

  • Java File class is a part of java.io package.
  • Java File class is an abstract representation of file and directory pathnames.
  • Operating systems uses system dependent pathnames to represent the file and directories but the java File class presents an abstract, system independent view of pathnames. This conversion of pathnames to or from an abstract pathname is inherently system dependent.
  • The parent of abstract pathname can bet fetch by calling getParent() method of File class.

Java File Constructors

We can create an instance of File class using below constructors.

  1. File(File parent, String child): Using this constructor we can create an instance of File class from specified parent abstract pathname and a child pathname string.
  2. File(String pathname): Using this constructor we can create an instance of File class from specified string pathname by converting it into an abstract pathname.
  3. File(String parent, String child): Using this file constructor we can create an instance of File class from specified parent and child pathname.
  4. File(URI uri): We can create an instance of File class from specified URI by converting it into abstract pathname.

Let’s have a look at the below program to show different way to create java.io.File instance.


package com.journaldev.examples;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
/**
 * Java File Constructor Example
 *
 * @author pankaj
 *
 */
public class FileConstructor {
	public static void main(String[] args) {
		//First
		File file = new File("D:/pankaj/data/file.txt");
		//Second
		File parent = new File("D:/pankaj/");
		File file2 = new File(parent, "data2/file2.txt");
		//Third
		File file3 = new File("D:/pankaj/", "data3/file3.txt");
		System.out.println("First : "+file.getAbsolutePath());
		System.out.println("Second : "+file2.getAbsolutePath());
		System.out.println("Third : "+file3.getAbsolutePath());
		//Forth
		URI uri;
		try {
			uri = new URI("file:///D:/pankaj/data4/file4.txt");
			File file4 = new File(uri);
			System.out.println("Forth : "+file4.getAbsolutePath());
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}
}

Output of the above program is:


First : D:pankajdatafile.txt
Second : D:pankajdata2file2.txt
Third : D:pankajdata3file3.txt
Forth : D:pankajdata4file4.txt

Java File Methods

Let’s have a look at the below methods of File class.

  1. canExecute(): This method tests if an application can execute the file that is denoted by this abstract pathname and returns either true or false.
  2. canRead(): This method tests if an application can read the file that is denoted by this abstract pathname and returns either true or false.
  3. canWrite(): This method tests if an application can modify the file that is denoted by this abstract pathname and returns either true or false.
  4. compareTO(File pathname): This method compare two abstract pathnames lexicographically and returns integer value.
  5. createNewFile(): This method automatically creates new empty file named by this abstract pathname if and only if a file with this name does not exist and returns either true or false.
  6. createTempFile(String prefix, String suffix): This is a static method and creates an empty file in the default temporary-file directory using specified prefix and suffix strings to generate file name and returns file object.
  7. createTempFile(String prefix, String suffix,  File directory): This is a static method and creates an empty file in specified directory using specified prefix and suffix strings to generate file name and returns file object.
  8. delete(): This method deletes the file or directory denoted by this abstract pathname and returns either true or false.
  9. deleteOnExit(): This method requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates and this is void method.
  10. exists(): This method checks whether the file or directory denoted by this abstract pathname is exists or not and based one that it will returns either true or false.
  11. getAbsoluteFile(): This method returns the absolute form of this abstract pathname.
  12. getAbsolutePath(): This methods returns absolute pathname string of this abstract pathname.
  13. getCanonicalFile(): This method returns canonical form of this abstract pathname.
  14. getCanonicalPath(): This method returns canonical pathname string of this abstract pathname.
  15. getName(): This method returns the name of file or directory denoted by this abstract pathname.
  16. isDirectory(): This method checks if the file denoted by this abstract pathname is directory or not and based on that it will returns either true or false.
  17. isFile(): This method checks if the file denoted by this abstract pathname is normal file or not and based on that it will return either true or false.
  18. isHidden(): This method checks if the file denoted by this abstract pathname is hidden file or not and based on that it will return either true or false.
  19. list(): This method returns an array of strings which contains naming of file or directories in the directory denoted by this abstract pathname.
  20. listFiles(): This method returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
  21. mkdir(): This method creates the directory named by this abstract pathname and returns either true or false.
  22. renameTo(File dest): This method renames the file denoted by this abstract pathname and returns either true or false.
  23. setReadable(boolean readable): This method sets owner’s read permission for this abstract pathname and returns either true or false.
  24. setReadable(boolean readable, boolean ownerOnly): This method sets owner’s or everybody’s read permission for this abstract pathname and returns either true or false.
  25. setReadOnly(): This method marks he file or directory named by this abstract pathname so that only read operation s are allowed and it returns either true or false.
  26. setWritable(boolean writable): This method sets owner’s write permission for this abstract pathname and returns either true or false.

Let’s look at some java file handling operations now.

Create New File

Java File class provides a createNewFile() method, which automatically creates new empty file named by this abstract pathname if and only if a file with this name does not exist.

This method returns true if new file created and false if file already exists and it throws java.io.IOException when it’s not able to create the file.

Let’s have a look at the below program to create a new file.


package com.journaldev.examples;
import java.io.File;
import java.io.IOException;
/**
 * Java Create File Program
 *
 * @author pankaj
 *
 */
public class FileCreateExample {
	public static void main(String[] args) {
		//initialize File constructor
		File file = new File("D:/data/file.txt");
		try {
			boolean createFile = file.createNewFile();
			if (createFile) {
				System.out.println("New File is created.");
			}else {
				System.out.println("File already exists.");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Check this post for more about Create New File in Java.

Create Temporary File

Java File class provides static createTempFile() method to create temporary file and this method has two variants – createTempFile(String prefix, String suffix) and createTempFile(String prefix, String suffix, File directory).


package com.journaldev.examples;
import java.io.File;
import java.io.IOException;
/**
 * Java Create Temporary File Program
 *
 * @author pankaj
 *
 */
public class CreateTempFileExample {
	public static void main(String[] args) {
		try {
			File tempFile = File.createTempFile("tempFile", ".tmp");
			System.out.println("Temp File Path : "+tempFile.getAbsolutePath());
			File directory = new File("D:/data");
			File tempFile1 = File.createTempFile("tempFile", ".tmp", directory);
			System.out.println("Temp File Path : "+tempFile1.getAbsolutePath());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output of the above program is below:


Temp File Path : C:UserspankajAppDataLocalTemptempFile4343440774354944188.tmp
Temp File Path : D:datatempFile908226099795027557.tmp

Check File Permissions

Java File class provides several methods to check file permissions (Execute/Read/Write) – canExecute(), canRead() and canWrite().


package com.journaldev.examples;
import java.io.File;
/**
 * Java Check File Permission Program
 *
 * @author pankaj
 *
 */
public class FilePermissionExample {
	public static void main(String[] args) {
		//initialize File constructor
		File file = new File("D:/data/file.txt");
		System.out.println("File is readable? "+file.canRead());
        System.out.println("File is writable? "+file.canWrite());
        System.out.println("File is executable? "+file.canExecute());
	}
}

Check this post for more about Java File Permissions.

Check if File already exists?

Java File class provides exists() method that checks whether the file or directory exists or not.

This method returns true if file or directory exists or else returns false.


package com.journaldev.examples;
import java.io.File;
/**
 * Java Check for File Exists Program
 *
 * @author pankaj
 *
 */
public class CheckForFileExistExample {
	public static void main(String[] args) {
		// initialize File constructor
		File file = new File("D:/data/file.txt");
		System.out.println("File Exists : "+file.exists());
		File nonExistfile = new File("D:/data/nofile.txt");
		System.out.println("File Exists : "+nonExistfile.exists());
	}
}

How to check if file is a directory?

Java File class provides isDirectory() method that checks if the file is directory or not. If it’s a directory then it will return true or else return false.


package com.journaldev.examples;
import java.io.File;
/**
 * Java Check if File is Directory Program
 *
 * @author pankaj
 *
 */
public class CheckFileIsDirectoryExample {
	public static void main(String[] args) {
		// initialize File constructor
		File file = new File("D:/data/");
		System.out.println("IS Directory? : "+file.isDirectory());
		File file2 = new File("D:/data/file.txt");
		System.out.println("IS Directory? : "+file2.isDirectory());
	}
}

Output of the above program is below:


IS Directory? : true
IS Directory? : false

File Path Separator

Java File class contains four static separator variables for path separators:

  1. pathSeparator: This is a system dependent path separator character and represented as a string.
  2. pathSeparatorChar: This is a system dependent path separator character.
  3. separator: This is a system dependent default name separator character and represented as a string.
  4. separatorChar: This is a system dependent default name separator character.

package com.journaldev.examples;
import java.io.File;
/**
 * Java File separator Program
 *
 * @author pankaj
 *
 */
public class FileSeparatorExample {
	public static void main(String[] args) {
		System.out.println("separator = "+File.separator);
        System.out.println("separatorChar = "+File.separatorChar);
        System.out.println("pathSeparator = "+File.pathSeparator);
        System.out.println("pathSeparatorChar = "+File.pathSeparatorChar);
	}
}

Output of the above program on Windows system:


separator =
separatorChar =
pathSeparator = ;
pathSeparatorChar = ;

Check this post for more about Java File Path Separator.

Java File Absolute & Canonical Path

Java File class provides two methods to fetch absolute and canonical path – getAbsolutePath() and getCanonicalPath(). Below example code will clear any confusion around the difference between them.


package com.journaldev.examples;
import java.io.File;
import java.io.IOException;
public class AbsoluteAndCanonicalPathExample {
	public static void main(String[] args) throws IOException {
		File file = new File("/Users/pankaj/source.txt");
		File file1 = new File("/Users/pankaj/temp/../source.txt");
		System.out.println("Absolute Path : " + file.getAbsolutePath());
		System.out.println("Canonical Path : " + file.getCanonicalPath());
		System.out.println("Absolute Path : " + file1.getAbsolutePath());
		System.out.println("Canonical Path : " + file1.getCanonicalPath());
	}
}

Output of the above program is:


Absolute Path : /Users/pankaj/source.txt
Canonical Path : /Users/pankaj/source.txt
Absolute Path : /Users/pankaj/temp/../source.txt
Canonical Path : /Users/pankaj/source.txt

java-file-path
Check this post for more about Java File Absolute & Canonical Path

Delete File in Java

Java File class provides delete() method that deletes the file or directory denoted by this abstract pathname. If it’s a directory then it should be empty, otherwise it won’t be deleted. This method returns true if file gets deleted or else returns false.


package com.journaldev.examples;
import java.io.File;
/**
 * Java File delete Example
 *
 * @author pankaj
 *
 */
public class FileDeleteExample {
	public static void main(String[] args) {
		// initialize File constructor
		File file = new File("D:/data/file.txt");
		boolean delete = file.delete();
		if (delete) {
			System.out.println("File Deleted");
		} else {
			System.out.println("File not Deleted");
		}
	}
}

Create Directories

Java File class provides two methods to create directories which are given below.

  1. mkdir(): This method creates the directory named by this abstract pathname. It creates only single directory and returns true if the directory gets created or else returns false.
  2. mkdirs(): This method creates the directory named by this abstract pathname including subdirectories and returns true if directories gets created or else returns false.

package com.journaldev.examples;
import java.io.File;
/**
 * Java Create Direcories Example
 *
 * @author pankaj
 *
 */
public class CreateDirectoriesExample {
	public static void main(String[] args) {
		// initialize File constructor
		File file = new File("D:/pankaj/");
		boolean created = file.mkdir();
		if (created) {
			System.out.println("Directory created");
		} else {
			System.out.println("Directory is not created");
		}
		//create directories including sub directories
		File file2 = new File("D:/pankaj/data/java");
		boolean creatSub = file2.mkdirs();
		if (creatSub) {
			System.out.println("Directory including sub directories created");
		} else {
			System.out.println("Directory including sub directories are not created");
		}
	}
}

Create Directories using Files Class

java.nio.Files class provides two static methods – createDirectory() and createDirectories() to create directories.


package com.journaldev.examples;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
 * Java Create Direcories Using Java 7 Example
 *
 * @author pankaj
 *
 */
public class CreateDirectoriesExample {
	public static void main(String[] args) {
		Path path = Paths.get("D:/java7");
		Path subPath = Paths.get("D:/java7/createdir/data");
		try {
			Path dirPath = Files.createDirectory(path);
			Path subdirPath = Files.createDirectories(subPath);
			System.out.println("Directory Path : "+dirPath);
			System.out.println("Directory Including sub Directories Path : "+subdirPath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

If the directory already exists it will throws java.nio.file.FileAlreadyExistsException exception.


package com.journaldev.examples;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
 * Java Create Direcories Using Java 7 Example
 *
 * @author pankaj
 *
 */
public class CreateDirectoriesExample {
	public static void main(String[] args) {
		Path path = Paths.get("D:/pankaj");
		try {
			Files.createDirectory(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Exception raised by above program is:


java.nio.file.FileAlreadyExistsException: D:pankaj
	at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
	at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
	at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
	at sun.nio.fs.WindowsFileSystemProvider.createDirectory(Unknown Source)
	at java.nio.file.Files.createDirectory(Unknown Source)
	at com.journaldev.examples.CreateDirectoriesExample.main(CreateDirectoriesExample.java:20)
java-file-example

List of Files in Directory

We can use listFiles() method, which returns an array of abstract pathnames denoting the files in the directory.


package com.journaldev.examples;
import java.io.File;
/**
 * Java Fetch List of File from Directory Example
 *
 * @author pankaj
 *
 */
public class FileListInDirectoryExample {
	public static void main(String[] args) {
		// initialize File constructor
		File dir = new File("D:/pankaj");
		File[] files = dir.listFiles();
		System.out.println("Files in Directory:");
		for (File file : files) {
			System.out.println(file.getAbsolutePath());
		}
	}
}

That’s all for java File class. Check out Java IO Tutorial to learn more about java File class and other interesting classes of java.io package.

By admin

Leave a Reply

%d bloggers like this: