Creating a New File in Java
Learn to create a new file using different techniques including NIO Path, IO File, OutputStream, and open-source libraries such as Guava and Apache commons.
1. Create New File using Java NIO
The Files.createFile(path, attribs) is the best way to create a new, empty and writable file in Java and it should be your preferred approach in the future if you are not already using it.
- The createFile() method takes the Path interface instead of the File. It checks if the file already exists, and creates the file thereafter.
- Checking any existing file and creating the file is done in a single atomic operation.
- The attribs an optional list of file attributes to set atomically when creating the file.
- It returns FileAlreadyExistsException If a file of that name already exists.
- It returns IOException if an I/O error occurs or the parent directory does not exist.
Example 1: Create a new writable file
String TEXT_FILE = "C:/temp/io/textFile.txt"; Path textFilePath = Paths.get(TEXT_FILE); Files.createFile(textFilePath);
Example 2: Create a new read-only file
Set the file attributes while creating the file. In the given example, we are setting read-only (“ r “) access for the owner, group, and others using the string “r–r–r–“.
String TEXT_FILE = "C:/temp/io/textFile.txt"; Set permissions = PosixFilePermissions .fromString("r--r--r--"); FileAttribute attribs = PosixFilePermissions .asFileAttribute(permissions); Path textFilePath = Paths.get(TEXT_FILE); Files.createFile(textFilePath, attribs);
2. Using File.createNewFile()
Use File.createNewFile() method to create a new file if and only if a file with this name does not yet exist. Checking any existing file and creating the file is an atomic operation.
This method returns a boolean value –
- true if the file is created successfully.
- false if the file already exists.
- IOException If an I/O error occurred.
String TEXT_FILE = "C:/temp/io/textFile.txt"; File textFile = new File(TEXT_FILE); boolean isFileCreated = textFile.createNewFile();
The constructor automatically creates a new file in the given location. Note that if a file with a given name already exists, it will be overwritten.
It throws FileNotFoundException if the given file path represents a directory, or a new file cannot be created for any reason.
String TEXT_FILE = "C:/temp/io/textFile.txt"; try(FileOutputStream fos = new FileOutputStream(TEXT_FILE))< // We can write data as byte[] // fos.write(data, 0, data.length); >
To include Guava, add the following to pom.xml.
com.google.guava guava 31.1-jre
The Files.touch() method is similar to the Unix touch command. It creates an empty file or updates the last updated timestamp
The touch command, when used without any option, creates an empty file assuming the file doesn’t exist. If the file exists it changes the timestamp.
String TEXT_FILE = "C:/temp/io/textFile.txt"; com.google.common.io.Files.touch(new File(TEXT_FILE));
5. Apache Commons IO’s FileUtils
To include Apache Commons IO, add the following to pom.xml.
The FileUtils.touch() is very similar to the previous example. It also implements the same behavior as the “touch” utility on Unix.
Also, as from v1.3 this method creates parent directories if they do not exist. It throws an IOException if the last modified date of the file cannot be set.
String TEXT_FILE = "C:/temp/io/textFile.txt"; org.apache.commons.io.FileUtils.touch(new File(TEXT_FILE));
Java Create and Write To Files
To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try. catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):
Example
import java.io.File; // Import the File class import java.io.IOException; // Import the IOException class to handle errors public class CreateFile < public static void main(String[] args) < try < File myObj = new File("filename.txt"); if (myObj.createNewFile()) < System.out.println("File created: " + myObj.getName()); >else < System.out.println("File already exists."); >> catch (IOException e) < System.out.println("An error occurred."); e.printStackTrace(); >> >
To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the » \ » character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt
Example
File myObj = new File("C:\\Users\\MyName\\filename.txt");
Write To a File
In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method:
Example
import java.io.FileWriter; // Import the FileWriter class import java.io.IOException; // Import the IOException class to handle errors public class WriteToFile < public static void main(String[] args) < try < FileWriter myWriter = new FileWriter("filename.txt"); myWriter.write("Files in Java might be tricky, but it is fun enough!"); myWriter.close(); System.out.println("Successfully wrote to the file."); >catch (IOException e) < System.out.println("An error occurred."); e.printStackTrace(); >> >
To read the file above, go to the Java Read Files chapter.
Creating file in Java
In Java create file tutorial, we show how to create a file in Java. We create files with built-in classes including File , FileOutputStream , and Files . We also use two third-party libraries: Apache Commons IO and Google Guava.
A is a computer resource for recording data discretely in a computer storage device.
The tutorials shows five ways to create a file in Java. The examples create empty files.
Java creating file with File
The File’s createNewFile method creates a new, empty file named by the pathname if a file with this name does not yet exist.
package com.zetcode; import java.io.File; import java.io.IOException; public class JavaCreateFileEx < public static void main(String[] args) throws IOException < File file = new File("src/main/resources/myfile.txt"); if (file.createNewFile()) < System.out.println("File has been created."); >else < System.out.println("File already exists."); >> >
The createNewFile returns true if the named file does not exist and was successfully created; false if the named file already exists.
Java creating file with FileOutputStream
In the second example, we create a new, empty file with FileOutputStream .
package com.zetcode; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class JavaCreateFileEx2 < public static void main(String[] args) throws FileNotFoundException, IOException < FileOutputStream fout = null; try < fout = new FileOutputStream("src/main/resources/myfile.txt"); >finally < if (fout != null) < fout.close(); >> > >
The file is created when FileOutputStream object is instantiated. If the file already exists, it is overridden.
FileNotFoundException is thrown if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason.
Java creating file with Files
Java 7 introduced Files , which consists exclusively of static methods that operate on files, directories, or other types of files. Its createFile method creates a new and empty file, failing if the file already exists.
package com.zetcode; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class JavaCreateFileEx3 < public static void main(String[] args) throws IOException < Path path = Paths.get("src/main/resources/myfile.txt"); try < Files.createFile(path); >catch (FileAlreadyExistsException ex) < System.err.println("File already exists"); >> >
The example creates a new, empty file with Files .
Path path = Paths.get("src/main/resources/myfile.txt");
A Path object is created. It is used to locate a file in a file system.
The new file is created with Files.createFile .
> catch (FileAlreadyExistsException ex)FileAlreadyExistsException is thrown if the file already exists.
Java creating file with Apache Commons IO
The next example creates a file with Apache Commons IO library.
For the project we need the commons-io dependency.
package com.zetcode; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class JavaCreateFileEx4 < public static void main(String[] args) throws IOException < FileUtils.touch(new File("src/main/resources/myfile.txt")); >>The new file is created with FileUtils.touch method.
Java creating file with Google Guava
In the following example, we create a new file with Google Guava library.
com.google.guava guava 23.4-jre For the project we need the guava dependency.
package com.zetcode; import com.google.common.io.Files; import java.io.File; import java.io.IOException; public class JavaCreateFileEx5 < public static void main(String[] args) throws IOException < Files.touch(new File("src/main/resources/myfile.txt")); >>The new file is created with Files.touch . It accepts a File as a parameter.
In this article we have shown several ways how to create a file in Java. We have used built-in tools and third-party libraries.
Author
My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.