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 writing 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.
Remember that this method will only create a file, but not write any content to it.
Example
// Java program to demonstrate createNewFile() method
import java.io.File;
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 (Exception e) {
System.err.println(e);
}
}
}
When you compile and run the program, it will have the following result:
Result
File created
Use 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 method 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 it’s usage:
Example
String fileData = "Some Test";
FileOutputStream fos = new FileOutputStream("D:\\example.txt");
fos.write(fileData.getBytes());
fos.flush();
fos.close();
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:
- lines - An object to iterate over the char sequences. Write lines of text to a file. Each line is a character sequence and is written to the file in sequence with each line terminated by the platform’s line separator.
- 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.
- path - Specifies the path to the line.
- cs - The charset to use for encoding.
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
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();
}
}
}