How to Create a File in Java
In Java, creating a file is easy by using pre-defined classes and packages. There are three ways to create a file.
Java File.createNewFile() method
The File.createNewFile() is a method of File class which belongs to a java.io package. It does not accept any argument. The method automatically creates a new, empty file. The method returns a boolean value:
When we initialize File class object, we provide the file name and then we can call createNewFile() method of the File class to create a new file in Java.
The File.createNewFile() method throws java.io.IOException if an I/O error occurred. It also throws SecurityException if a security manager exists and its SecurityManager.checkWriter(java.lang.String) method denies write access to the file. The signature of the method is:
We can pass the file name or absolute path or relative path as an argument in the File class object. For a non-absolute path, File object tries to locate the file in the current directory.
The following example creates a new, empty text file. The first run creates music.txt successfully while on the second run it failed. We can create any type of file by changing the file extension only.
When file does not exists.
When file already exists.
A file Output stream writes data to a file. Java FileOutputStream class also provide support for files. It belongs to the java.io package. It stores the data into bytes. We use FileOutputStream class when we need to write some data into the created file. The FileOutputStream class provides a constructor to create a file. The signature of the constructor is:
name: is the file name
append: if true, byte will be written to the end of the file, not in the beginning.
In the following example, we have created a file using FileOutputStream.
Java File.createFile() method
The File.createFile() is a method of File class which belongs to java.nio.file package. It also provides support for files. The nio package is buffer-oriented. The createFile() method is also used to create a new, empty file. We don't need to close the resources when using this method. It is an advantage. The signature of the method is:
Path: The path of the file.
Attribute: An optional list of file attributes.
The method returns the file.
The following example also creates a new, empty file. We create a Path instance using a static method in the Paths class (java.nio.file.Paths) named Paths.get(). Notice the following statement:
Path path = Paths.get("C:\\demo\\javaprogram.txt");
In the above line Path is an interface and Paths is a class. Both belongs to same package. The Paths.get() method creates the Path Instance.