w3docs logo
  1. Snippets
  2. Java
  3. How to Create a File in Java

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.

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.


// 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");
                System.out.println("File already exists");
        catch (Exception e) {

When you compile and run the program, it will have the following 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:


String fileData = "Some Test";
FileOutputStream fos = new FileOutputStream("D:\\example.txt");

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.


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) {


Do you find this helpful?