java-how-to-create-a-file
Java – Create a File
In this quick tutorial we’re going to learn how to create a new File in Java – first using JDK6, then the newer JDK7 with NIO and finally the Apache Commons IO library.
This article is part of the “Java – Back to Basic” series here on Baeldung.
1. With Java – JDK 6
@Test
public void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
File newFile = new File("src/test/resources/newFile_jdk6.txt");
boolean success = newFile.createNewFile();
assertTrue(success);
}
Note that the file must not exist for this operation to succeed; if the file does exist, then createNewFile operation will return false.
2. With Java – JDK 7
@Test
public void givenUsingJDK7nio2_whenCreatingFile_thenCorrect()
throws IOException {
Path newFilePath = Paths.get("src/test/resources/newFile_jdk7.txt");
Files.createFile(newFilePath);
}
As you can see the code is still very simple; we’re now using the new Path interface instead of the old File.
One thing to note here is that the new API makes good use of exceptions – if the file already exists, we no longer have to check a return code – we get a FileAlreadyExistsException instead:
java.nio.file.FileAlreadyExistsException: srctestresourcesnewFile_jdk7.txt
at sun.n.f.WindowsException.translateToIOException(WindowsException.java:81)
3. With Guava
@Test
public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
Files.touch(new File("src/test/resources/newFile_guava.txt"));
}
4. With Commons IO
Apache Commons provides the FileUtils.touch() method which implements the same behavior as the “touch” utility in Linux – it creates a new empty file or even a file and full path to it in a file system:
@Test
public void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt"));
}
Note that this behaves slightly differently than the previous examples – if the file already exists, the operation doesn’t fail – it simply doesn’t do anything.
And there we have it – 4 quick ways to create a new file in Java.