In this Java tutorial we show you various code examples that demonstrate how to use the legacy File IO API for common file IO operations. You will know how to create, rename, copy, delete, read attributes, set permissions, etc of a file or directory.

You know, the java.io.File class provides many useful methods for working with files and directories. Hence most of the following examples are based on this class.

Note that most of the File’s methods return true indicating the operation succeeded, or return false otherwise. They also throw a SecurityException if the user doesn’t have appropriate permission.

Here’s the list of examples:

1. Create an Empty File

2. Create a Temporary File

3. Create a Directory

4. List Content of a Directory

5. Rename a File or Directory

6. Delete a File or Directory

7. Read File Information

8. Read and Set File Permissions

9. Getting Disk Drives Information

10. Copy a File

 

1. Create an Empty File

Use the createNewFile() method on a File object to create a new empty file. This method returns true if the file created successfully, and returns false if the file already exist. The following code creates an empty file with Windows-based absolute path:

try {

	File file = new File("E:\\Java\\Test\\FileIO\\Code.java");
	boolean created = file.createNewFile();

	if (created) {
		System.out.println("The file has been created");
	}

} catch (IOException ex) {
	System.err.println(ex.getMessage());
}
And to create a file on Linux-based operating systems, construct a file with the path like this:

File file = new File("/home/yourname/Java/Code.java");
To create a file in the current directory (same as the current running program’s directory):

File file = new File("Code.java");
You can use the constant File.separatorto construct a path name which is system-dependent and don’t worry about Linux or Windows, for example:

String userHomeDir = System.getProperty("user.home");
String path = userHomeDir + File.separator + "Code.java";

File file = new File(path);
boolean created = file.createNewFile();


This creates a file name Code.java under the user’s home directory.

 

2. Create a Temporary File

Use the static method createTempFile() to create a file in the system’s temporary directory. The system decides the actual file name, and you just suggest the prefix and suffix. The following example creates a text file in the system’s temporary directory and writes a single line of text to it:

try {
	File tempFile = File.createTempFile("CodeJava", ".log");
	BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
	writer.write("I love Java");
	writer.close();

} catch (IOException ex) {
	System.err.println(ex.getMessage());
}
You will see a file whose name looks something like CodeJava6649987320877041676.log in the temporary directory.

 

3. Create a Directory

Use the mkdir() method to create a single directory. This method returns true if the directory was created, and false otherwise, e.g. the directory already exists. The following example creates a directory in the current directory:

File newDir = new File("CodeJava");

if (newDir.mkdir()) {
	System.out.println("Directory created");
} else {
	System.out.println("Directory not created");
}
You can also use the mkdirs()method to create nested directories, for example:

File newDir = new File("CodeJava\\FileIO\\Examples");

if (newDir.mkdirs()) {
	System.out.println("Directories created");
} else {
	System.out.println("Directories not created");
}
This creates three nested directories in the current directory: CodeJava\FileIO\Examples.

 

4. List Content of a Directory

Use the list() method on a File object to list the content of a directory. This method returns an array of Strings naming the files and directories in the specified directory.  Here’s an example:

File userHomeDir = new File(System.getProperty("user.home"));

String[] content = userHomeDir.list();

for (String entry : content) {
	System.out.println(entry);
}
This prints the content of the user’s home directory.

You can supply a FilenameFilter to another overload of the list() method to list only files and directories that satisfy a condition. For example, the following code lists only .java files in the current directory:

File currentDir = new File(".");

FilenameFilter filter = new FilenameFilter() {
	public boolean accept(File file, String name) {
		return name.endsWith(".java");
	}
};

String[] content = currentDir.list(filter);

for (String entry : content) {
	System.out.println(entry);
}
Similarly, the methods listFiles() and listFiles(FilenameFilter)do the same, but return an array of File objects.

For more examples about listing a directory (including listing recursively), see this article: How to list files and directories in a directory.

 

5. Rename a File or Directory

Use the renameTo(File) method on a File object to rename an existing file or directory. This method returns true if the file/directory was renamed, or false otherwise (e.g. the original file/directory does not exist). Here’s an example:

File oldName = new File("CodeJavaLogoBig.png");
File newName = new File("CodeJavaLogoSmall.png");

boolean renamed = oldName.renameTo(newName);

if (renamed) {
	System.out.println("The file was renamed");
} else {
	System.out.println("Could not rename");
}
This renames the file CodeJavaLogoBig.png to CodeJavaLogoSmall.png. You can use this method to move a file or directory to another location, however it is platform-dependent, which means it may work on this operating system but not on others.

 

6. Delete a File or Directory

Use the delete() method on a File object to delete an existing file or directory (non-empty). This method returns true if the file/directory was deleted, or false otherwise (e.g. the file/directory does not exist). It throws SecurityException if the user doesn’t have permission. Here’s an example:

File file = new File("CodeJavaLogoSmall.png");

if (file.delete()) {
	System.out.println("The file was deleted");
} else {
	System.out.println("Could not delete the file");
}
To delete a non-empty directory, you must delete all the files and sub directories within it. See: Clean and remove a non-empty directory.

You can invoke the deleteOnExit() method to tell the Java Virtual Machine deletes the file when the program exits and the JVM terminates. This is useful for deleting temporary files used by a program.

 

7. Read File Information

There are several other methods that can be used to query additional information of an existing file. They are:

  • boolean exists(): tells whether a file or directory exists or not.
  • String getAbsolutePath():  returns the absolute path of a file or directory.
  • String getName(): returns only the name portion in the full path a file or directory.
  • String getParent(): returns the name of the parent directory, or null if not specified.
  • File getParentFile(): returns a File object represents the parent directory, or null if not specified.
  • boolean isDirectory(): tells whether this file is a directory or not.
  • boolean isFile(): tells whether this file is a normal file or not.
  • boolean isHidden(): tells whether this file or directory is hidden or not.
  • long lastModified(): returns the last modified time of a specified file or directory in milliseconds.
  • length(): returns the size of a specified file in bytes. It returns 0 if the file does not exist or is a directory.
And here’s an example that uses all of the above methods:

File file = new File("CodeJavaLogoSmall2.png");
boolean existed = file.exists();
String absolutePath = file.getAbsolutePath();
String name = file.getName();
String parent = file.getParent();
File parentFile = file.getParentFile();
boolean isDirectory = file.isDirectory();
boolean isFile = file.isFile();
boolean isHidden = file.isHidden();
Date lastModified = new Date(file.lastModified());
long size = file.length();

System.out.println("Existed? " + existed);
System.out.println("Absolute Path = " + absolutePath);
System.out.println("Name = " + name);
System.out.println("Parent = " + parent);
System.out.println("Parent File = " + parentFile);
System.out.println("Is Directory = " + isDirectory);
System.out.println("Is File = " + isFile);
System.out.println("Is Hidden = " + isHidden);
System.out.println("Last Modified = " + lastModified);
System.out.println("Size = " + size);
 

8. Read and Set File Permissions

You can use the following methods to query the read/write/execute permissions of a given file:

  • boolean canRead(): tells whether the program can read the file.
  • boolean canWrite(): tells whether the program can modified the file.
  • boolean canExecute(): tells whether the program can execute the file.
And use the following methods to set the read only/write/execute permissions of a file:

  • boolean setReadOnly(): marks the file or directory as read-only.
  • boolean setWritable(boolean writable): sets write permission for the owner of a file or directory.
  • boolean setWritable(boolean writable, boolean ownerOnly): sets write permission for everybody or the owner of a file or directory.
  • boolean setExecutable(boolean):  sets execute permission for the owner of a file.
  • boolean setExecutable(boolean writable, boolean ownerOnly):  sets execute permission for everybody or the owner of a file.
These methods return true if the operations succeeded, false otherwise, and throw SecurityException if the user doesn’t have write permission.

For example, the following code sets a file to read-only:

File file = new File("CodeJavaLogoSmall.png");

if (file.canWrite()) {
	if (file.setReadOnly()) {
		System.out.println("The file was set to read-only");
	}
}
In addition, you can use the setLastModified() method to set the last-modified time of a file or directory, for example:

File file = new File("CodeJavaLogoSmall.png");
long currentTime = System.currentTimeMillis();

if (file.setLastModified(currentTime)) {
	System.out.println("File's last-modified was updated");
}
This sets the last-modified time of the file to the current time.

 

9. Getting Disk Drives Information

Use the static method File.listRoots() to query all disk partitions managed by the operating system.

Use the getTotalSpace() method to query the size of a specified partition in bytes.

Use the getFreeSpace() method to query the free space of a specified partition in bytes.

For example, the following code list all drives and print the total space and free space of each:

File[] drives = File.listRoots();
if (drives != null && drives.length > 0) {
    for (File aDrive : drives) {
	System.out.println("Drive Letter: " + aDrive);
	System.out.println("\tTotal space: " + aDrive.getTotalSpace());
	System.out.println("\tFree space: " + aDrive.getFreeSpace());
	System.out.println();
    }
}
And here’s the output on my computer:

Drive Letter: C:\
        Total space: 73402363904
        Free space: 7710081024

Drive Letter: D:\
        Total space: 106151542272
        Free space: 5106290688
 

10. Copy a File

You can use a buffered input stream and buffered output stream to copy a file like this:

try (
		BufferedInputStream inputStream
			= new BufferedInputStream(new FileInputStream(inputFile));

		BufferedOutputStream outputStream
			= new BufferedOutputStream(new FileOutputStream(outputFile));
) {

    int byteRead;

    while ((byteRead = inputStream.read()) != -1) {
	outputStream.write(byteRead);
    }
} catch (IOException ex) {
	ex.printStackTrace();
}
However the above code is not efficient. Instead, you can use the FileChannel in the java.nio.channels package to copy a file more efficiently. The following method copies a source file to destination one using the FileChannel:

public static void copyFile(File sourceFile, File destFile) {
	try (
		FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel();
		FileChannel destChannel = new FileOutputStream(destFile).getChannel();
	) {
		sourceChannel.transferTo(0, sourceChannel.size(), destChannel);

	} catch (IOException ex) {
		System.err.println(ex.getMessage());
	}
}
To copy a whole directory recursively, see this example: How to copy a directory programmatically in Java

 

API Reference:

 

Other Java File IO Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment