Appearance
How to Create a File in Java
It is not a difficult thing to create a new file in Java. This article is to help beginners learn to create a new file and then write to it in Java.
So, firstly let’s learn creating new files in Java.
There are several ways of doing it. In this article, we are going to uncover three ways of creating files. Here we go.
Use the java.io.File class
When you initialize File object, you provide the file name and then call the createNewFile() method, which atomically creates a new, empty file named by the abstract pathname, if a file with that name does not yet exist.
This method returns true, if the named file does not exist and was successfully created. And returns false if the file exists. It also throws java.io.IOException when it’s not able to create the file. The created file is empty and has zero bytes.
DANGER
This method should not be used for file-locking, as the resulting protocol cannot be made to work reliably.
Remember that this method will only create a file, but not write any content to it.
Example
How to Create a File in Java
java
// Java program to demonstrate createNewFile() method
import java.io.File;
import java.io.IOException;
public class FileCreator {
public static void main(String args[])
{
try {
// Get the file
File f = new File("D:\\example.txt");
// Create new file
// Check if it does not exist
if (f.createNewFile())
System.out.println("File created");
else
System.out.println("File already exists");
}
catch (IOException e) {
System.err.println(e);
}
}
}When you compile and run the program, it will have the following result:
Result
How to Create a File in Java
text
File createdUse the java.io.FileOutputStream class
If you want to create a new file and at the same time write some data into it, you can use the FileOutputStream.write method. This method automatically creates a new file and writes some content to it.
The FileOutputStream class is used for writing streams of raw bytes such as image data. If you want to write character-oriented data, it is better to use the FileWriter.
Here find a simple code to see its usage:
Example
How to Create a File in Java
java
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCreator {
public static void main(String[] args) {
String fileData = "Some Test";
try (FileOutputStream fos = new FileOutputStream("D:\\example.txt")) {
fos.write(fileData.getBytes());
} catch (IOException e) {
System.err.println(e);
}
}
}Use the Java NIO Files.write()
Use Java NIO Files class for creating a new file and write some data into it. This Java class provides write(Path path, byte[] bytes, OpenOption… options) method that writes bytes to a file at specified path.
Using the Files class, it is possible to create, move, copy, delete files and directories. It also can be used to read and write to a file.
Files.write() is a preferable way for creating a file, because you will not worry about closing IO resources.
This class has the following parameters:
- path - Specifies the path to the file.
- bytes - The byte array to write to the file.
- options - This parameter specifies how the file is created or opened. If no option is specified then it consider CREATE, TRUNCATE_EXISTING and WRITE options by default. This means it opens the file for writing and creates if the file does not exist or truncate existing file to size of 0 if it exists.
All the bytes in byte array are written to the file. This method ensures that the file is closed when all the bytes have been written and returns the path of written file.
Example
How to Create a File in Java
java
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FilesWriterExample {
public static void main(String[] args) {
Path path = Paths.get("D:/data/example.txt");
try {
String str = "Some write file Example";
byte[] bs = str.getBytes();
Path writtenFilePath = Files.write(path, bs);
System.out.println("Written content in file:\n" + new String(Files.readAllBytes(writtenFilePath)));
} catch (Exception e) {
e.printStackTrace();
}
}
}