Skip to content

Java Create File | New Text File | If Not Exists and examples

  • by

Creating a new file in Java is not a big task. There are several ways to do Java to create the file. When you creating a file always give the right path and the name of the file should be easily understood.

Java Create File New Text File If Not Exists and examples

Ways to Create File in Java

Here are 3 ways to do it with used these java classes.

  • File.createNewFile()
  • FileOutputStream class
  • Java NIO

Let’s start with examples

We will see different ways to java create a file with examples. There is always a chance of exception so better use IOException and try-catch or exception handling in the program to prevent a crash application.

Create file with – file.createNewFile()

Package java.io is needed to start with File class and method createNewFile() to create Create a New File in Java application. When creating an object of File you have to pass the name of the file with the extension (with path if required).

createNewFile()  if-else statement will return a boolean result- true and false, where true means file created and false means failed to create a file. For that will show a message and check condition in the.

The complete code of an example of How to java create a new file.

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

public class FileCreating {

    public static void main(String[] args) {
        File file = new File("newFile.txt");

        //Create the file
        try {
            if (file.createNewFile()) {
                System.out.println("New Text File is created!");
            } else {
                System.out.println("File already exists.");
            }
            //Write Content
            FileWriter writer = new FileWriter(file);
            writer.write("Test data");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output: New Text File is created!

Gif Image for output and program code structure.

Java Create File example

FileOutputStream class

At a condition where you want a create and write data into a file using FileOutputStream.write() method automatically creates a new file and writes content to it.

See the below example of Java create a text file.

import java.io.FileOutputStream;
import java.io.IOException;

public class FileCreating {

    public static void main(String[] args) throws IOException {
        String data = "EyeHunt data";

        FileOutputStream out = new FileOutputStream("testFile.txt");

        out.write(data.getBytes());
        out.close();
    }
}

Java NIO Files.write()

This is the best approach to create a java file, it’s not needed to close IO resources. You can use the Java NIO Files class to create a new text file and write content into it.

Let’s see the example of it.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileCreating {

    public static void main(String[] args) {
        String content = "EyeHunt data";

        try {
            Files.write(Paths.get("newFile.txt"), content.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to Java create a file in the directory

The best way to create a file in Directory is –

String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);

f.getParentFile().mkdirs(); 
f.createNewFile();

Conclusion: Some Points you should be in mind when creating a file in java.

  • Check the file if exists or not then create it.
  • Write Program with exception Handling to prevent an application crash
  • Close the file stream after use to release all resources.

Question: How do I create a file and write to it in Java?

Answer: There are 2 approaches to create and write into the file using java programming language, as above mentioned is FileOutputStream class and Java NIO. Follow these ways as above example and explanation.

Do comment if you know more ways, we will add in post. And also if you have any doubt. Some example has checked the condition – create the file if not exists.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Java Create files are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.|

Leave a Reply

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