How to Create File in Java?

Hello everyone! I am glad to meet you again with a wonderful article. In java, two packages provide all the necessary classes and methods for file manipulation. They are the java.io package and the java.nio package. File creation is the basic step in file manipulation. In java, file creation is made simpler with many built-in methods and classes. In this article, we will gain information on the various ways to create a file in java. Let’s start!!

Different ways for file creation in java:

Some of the different ways to create a file in java are:

1. createNewFile()

2. FileOutputStream

3. FileWriter

4. createFile()

5. write()

6. writeString()

7. newBufferedWriter()

different ways for file creation in java

Let us try to understand each one of them with examples. In this article, We will create a file named FirstCode.txt in the following path.

E:\FirstCode

1. Java createNewFile():

The createNewFile() method is a part of the File class in the java.io package. This method helps us to create a new empty file in the specified path.

Method signature:

public boolean createNewFile() throws IOException

The return type of the createNewFile() method is a boolean. If the file creation is successful, it returns true. And if the file creation fails, it returns false. The common reason for the failure is that the file already exists in the given location. When the specified path is not available, it will throw an IOException.

Syntax:

File fileObject = new File(“absolute/relative path/file name”);
fileObject.createNewFile();

We will provide the file name, absolute path, or relative path as an argument to the file object at the initialization time. Then we use the createNewFile() method to create a new empty file in the given name in the specified path. If we provide a non-absolute path or file name alone, the fileObject creates the file in the current directory. The current directory is the folder where your java file is stored.

Consider the following program.

import java.io.File;
import java.io.IOException;

public class CreateFile {

    public static void main(String[] args) {
        try {
        //Creating a file object.
        File file = new File("E:\\FirstCode.txt");
        //Creating a new file.
        boolean result= file.createNewFile();
        //If the file creation is successful, it returns true. Or else it returns false.
        if(result) {
            System.out.println("The file is created at: "+file.getCanonicalPath());
        }
        else {
            System.out.println("The file already present at: "+file.getCanonicalPath());
        }
        }
        catch(IOException exception) {
            //If the specified path is wrong, it throws an IOException.
            System.out.println("The specified path is not available.");
        }
    }
}

Output:

  • If the file creation is successful, The output will be:

The file is created at: E:\FirstCode.txt

  • If the file already exists, the output is as shown:

The file already exists at: E:\FirstCode.txt

  • If the specified path is not available, the output will be:

The specified path is not available.

2. Java FileOutputStream:

The FileOutputStream is a part of the java.io package. This class deals with byte data. If the file exists at the given location, then the FileOutputStream writes the data into it. Or else it creates a new file in the given name and then writes the data into it.

Constructor signature:

You can use any of the constructors given below based on our needs.

public FileOutputStream(String file_name, boolean append) throws FileNotFoundException
public FileOutputStream(String file_name) throws FileNotFoundException
public FileOutputStream(File fileObject, boolean append) throws FileNotFoundException
public FileOutputStream(File fileObject) throws FileNotFoundException

The parameter append represents whether to add the data at the end of the file without overwriting the existing contents. The append value must be either true or false. If you do not want to overwrite the files, use the constructor with the append option.

Syntax:

FileOutputStream object = new FileOutputStream(“file_path/file_name”, append option);
Or
FileOutputStream object =new FileOutputStream(“file_path/file_name”);
Or
File fileObject = new File(“absolute/relative path/file name”);
FileOutputStream object =new FileOutputStream(fileObject);
Or
File fileObject = new File(“absolute/relative path/file name”);
FileOutputStream object =new FileOutputStream(fileObject, append option);

If we provide a non-absolute path or file name alone, the fileObject creates the file in the current directory. The current directory is the folder where your java file is stored.

Consider the following program.

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;

public class CreateFile {

    public static void main(String[] args) {
        try {
        //Creating File object.
        File file = new File("E:\\FirstCode.txt");
        //Creating FileOutputStream object.
        // Here, the append argument is true, so if the file already exists, it appends the content at the end. Or else it creates a new file and writes into it.
        FileOutputStream fos = new FileOutputStream(file, true);
        String content = "Welcome to FirstCode and DataFlair.\n";
        //Converting the content string to bytes.
        byte[] b = content.getBytes();
        //Writing the content into the file
        fos.write(b);
        //Closing the resource.
        fos.close();
        System.out.println("The file is created at: "+file.getCanonicalPath());
        }
        catch(FileNotFoundException exception) {
            //If the system path is not available, FileNotFoundException occurs.
            System.out.println("The specified path is not available.");
        }
        catch(Exception exception) {
            System.out.println("Invaid inputs.");
        }

    }
}

Output:

  • If the file creation is successful, The output will be:

The file is created at: E:\FirstCode.txt

  • If the file already exists, the output is as shown:

The file is created at: E:\FirstCode.txt

  • If the specified path is not available, the output will be:

The specified path is not available.

3. Java FileWriter:

FileWriter is also a part of the java.io package. We use the FileWriter class to write short content into the file. Unlike FileOutputStream, We can write the string content directly into the file without converting it into bytes. Here also, If the file already exists at the given location, then the FileWriter writes the data into it. Otherwise, it creates a new file in the given name and then writes the given data into it.

Constructor signature:

You can use any of the constructors given below based on our needs

public FileWriter(String fileName) throws IOException
public FileWriter(String fileName, Boolean append) throws IOException
public FileWriter(File fileObject) throws IOException
public FileWriter(File fileObject, Boolean append) throws IOException

The parameter append represents whether to add the data at the end of the file without overwriting the existing contents. The append value must be either true or false. If you do not want to overwrite the files, use the constructor with the append option.

Syntax:

FileWriter object = new FileWriter(“file_path/file_name”, append option);
Or
FileWriter object =new FileWriter(“file_path/file_name”);
Or
File fileObject = new File(“absolute/relative path/file name”);
FileWriter object =new FileWriter(fileObject);
Or
File fileObject = new File(“absolute/relative path/file name”);
FileWriter object = new FileWriter(fileObject, append option);

Consider the following program.

import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;

public class CreateFile {

    public static void main(String[] args) {
        try {
        //Creating File object.
        File file = new File("E:\\FirstCode.txt");
        //Creating FileWriter object.
        // Here, the append argument is true, so if the file already exists, it appends the content at the end. Or else it creates a new file and writes into it.
        FileWriter writer = new FileWriter(file, true);
        String content = "Welcome to FirstCode and DataFlair.\n";
         //Writing the content into the file
        writer.write(content);
        //Closing the resource.
        writer.close();
        System.out.println("The file is created at: "+file.getCanonicalPath());
        }
        catch(FileNotFoundException exception) {
            //If the system path is not available, it throws FileNotFoundException.
            System.out.println("The specified path is not available.");
        }
        catch(Exception exception) {
            System.out.println("Invaid inputs.");
        }

    }
}

Output:

  • If the file creation is successful, The output will be:

The file is created at: E:\FirstCode.txt

  • If the file already exists, the output is as shown:

The file is created at: E:\FirstCode.txt

  • If the specified path is not available, the output will be:

The specified path is not available.

4. Java createFile():

The createFile() method is a part of the Files class in java.nio package. This method creates a new empty file. The main advantage of this method is there is no need to close the resources like other methods listed above.

Method Signature:

public static Path createFile(Path, Attribute) throws IOException

This createFile() method returns a file.

The path parameter is the path instance of the file.

The attribute parameter represents the optional file attribute list.

Syntax:

Path pathObject = Paths.get(“file_path/ file_name”);
Path object = Files.createFile(pathObject);

First, we have to create a path instance followed by the createFile() method.

Consider the following Java Code.

import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateFile {

    public static void main(String[] args) {
        try {
            Path pathObject = Paths.get("E:\\FirstCode.txt");
            //Creating a file.
            Path object = Files.createFile(pathObject);
            System.out.println("File created.");
        }
        catch(NoSuchFileException exception) {
            //If the system path is not available, NoSuchFileException occurs.
            System.out.println("The specified path is not available.");
            
        }
        catch(FileAlreadyExistsException exception) {
            //If the file already exists, it throws FileAlreadyExistsException.
            System.out.println("The file already exists.");
            
        }
        catch(Exception exception) {
            System.out.println("Invaid inputs.");
        }
    }
}

Output:

  • If the file creation is successful, The output will be:

File created.

  • If the file already exists, the output is as shown:

The file already exists.

  • If the specified path is not available, the output will be:

The specified path is not available.

5. Java write():

The write() method is a part of the Files class in java.nio package. It also automatically closes the opened resources like the createFile() method. If the file is not present in the given location, This method creates a new file and writes the content into it. Or else it writes the content into the file. This method deals with bytes. It is used for writing short content and is unsuitable for longer ones.

Method Signature:

public static Path write(Path path, byte[] bytes, OpenOptions…) throws IOException

This write() method returns a file.

The path parameter is the path instance of the file.

The bytes parameter represents the content for writing in the file.

OpenOption represents the StandardOpenOption like StandardOpenOption.APPEND etc.

Syntax:

If you want to create a file and append the data to the end instead of overwriting it, you can specify the append option as shown below.

Files.write(Paths.get(“file_path/ file_name”),content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.APPEND));

Consider the following java program.

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class CreateFile {

    public static void main(String[] args) {
        try {
            String content = "Welcome to FirstCode and DataFlair";
            //Creating and Writing in the file. If the file already exists, it appends the content at the end. Or else it creates a new file and writes into it.
            Files.write(Paths.get("E:\\FirstCode.txt"), content.getBytes(StandardCharsets.UTF_8),StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            System.out.println("File created.");
        }
        catch(NoSuchFileException exception) {
            //If the system path is not available, it throws NoSuchFileException.
            System.out.println("The specified path is not available.");

        }
        catch(Exception exception) {
            
            System.out.println("Invalid inputs.");

        }
    }
}

Output:

  • If the file creation is successful, The output will be:

File created.

  • If the file already exists, the output is as shown:

File created.

  • If the specified path is not available, the output will be:

The specified path is not available.

6. Java writeString():

It is a new method in the Files class in java.nio package. This method writes the string or text into the given file. If the file is not present in the given location, This method creates a new file and writes the content into it. Or else it writes the content into the file. Unlike the write() method, it can directly write the string data into a file. There is no need to convert the string into bytes.

Method Signature:

public static Path writeString(Path path, CharSequence csq, OpenOptions...) throws IOException

This writeString() method returns a file.
The path parameter is the path instance of the file.
The second argument represents the Content in String type.
OpenOption represents the StandardOpenOption like StandardOpenOption.APPEND etc.
You can also add charset as the third argument.

Syntax:

Files.writeString(Paths.get(“file_path/ file_name”), content, StandardCharsets.UTF_8);

Here the third argument represents the charset, and it is optional.
Or
If you want to create a file and append the data to the end instead of overwriting it, you can specify the append option as shown below.

Path pathObject = Paths.get(“file_path/ file_name”);
Files.writeString(pathObject,content, StandardOpenOption.CREATE, StandardOpenOption.APPEND));

Consider the following java program.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.file.NoSuchFileException;

public class CreateFile {

    public static void main(String[] args) {
        try {
            //Creating a path instance.
            Path pathObject = Paths.get("E:\\FirstCode.txt");
            String content = "Welcome to FirstCode\n";
            //Creating and Writing in the file. If the file already exists, it appends the content at the end. Or else it creates a new file and writes into it.
            Files.writeString(pathObject, content,StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            System.out.println("File created.");
        }
        catch(NoSuchFileException exception) {
            //If the system path is not available, NoSuchFileException occurs.
            System.out.println("The specified path is not available.");

        }
        catch(Exception exception) {
            
            System.out.println("Invalid inputs.");

        }

    }
}

Output:

  • If the file creation is successful, The output will be:

File created.

  • If the file already exists, the output is as shown:

File created.

  • If the specified path is not available, the output will be:

The specified path is not available.

7. Java newBufferedWriter():

The newBufferedWriter() method is a part of the Files class in the java.nio.package. It is a new method added in Java8. If the file is available in the given location, the method writes the content into it. Otherwise, it creates a new file and then writes into it.

Method Signature:

public static BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOptions...)

Syntax:

Path pathObject = Paths.get(“file_path/ file_name”);
BufferedWriter writer = Files.newBufferedWriter(pathObject, StandardCharsets.UTF_8);
writer.write(content);

Here the charset argument is optional.
Or
If you want to create a file and append the data to the end instead of overwriting it, you can specify the append option as shown below.

Path pathObject = Paths.get(“file_path/ file_name”);
BufferedWriter writer = Files.newBufferedWriter(pathObject, StandardOpenOption.CREATE, StandardOpenOption.APPEND));
writer.write(content);

Here we use the writer object and write() method to write the content into the file.

Consider the following java program.

import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.NoSuchFileException;

public class CreateFile {

    public static void main(String[] args) {
        try {
            //Creating a path instance.
            Path pathObject = Paths.get("E:\\DataFlair\\FirstCode.txt");
            String content = "Welcome to FirstCode and DataFlair";
            //Creating a BufferedWriter object.
            BufferedWriter writer = Files.newBufferedWriter(pathObject);
            //Writing the content into the specified file.
            writer.write(content);
            //Close the BufferedWriter bbject.
writer.close();
            System.out.println("File created.");
        }
        catch(NoSuchFileException exception) {
            //If the system path is not available, NoSuchFileException occurs.
            System.out.println("The specified path is not available.");

        }
        catch(Exception exception) {
            System.out.println("Invalid inputs.");

        }

    }
}

Output:

  • If the file creation is successful, The output will be:

File created.

  • If the file already exists, the output is as shown:

File created.

  • If the specified path is not available, the output will be:

The specified path is not available.

Summary:

There are many ways to create a file in java, as discussed in this article. Choosing the right one based on your requirements is an important step. I hope this article helps you to learn about various methods to create a file in java. Thank you for reading this article. Have a happy programming journey.

Leave a Reply

Your email address will not be published. Required fields are marked *