Java - File Input Output Create Files

Introduction

Files class provides several methods to create regular files, directories, symbolic links, and temporary files/directories.

These methods throw an IOException when an I/O error occurs during the file creation.

They throw an IOException if you attempt to create a file that already exists.

Most of the methods accept a varargs parameter of the FileAttribute type, which lets you specify the file attributes.

You can use the createFile() method to create a new regular file.

The file creation fails in case the file already exists, or the parent directory does not exist.

The following code shows how to create a new file. It attempts to create a Main.java file in your default directory.

The program prints the details of the file creation status.

Demo

import java.io.IOException;
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 Main {
  public static void main(String[] args) {
    Path p1 = Paths.get("test.txt");
    try {/*w ww.j  av  a2  s  . c o m*/
      Files.createFile(p1);
      System.out.format("File created: %s%n", p1.toRealPath());
    } catch (FileAlreadyExistsException e) {
      System.out.format("File %s already exists.%n", p1.normalize());
    } catch (NoSuchFileException e) {
      System.out.format("Directory %s does not exists.%n", p1.normalize()
          .getParent());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result