Java - How to create a text file

Introduces different ways to create files in Java.

  • Created using File
  • Created using Path and Files
  • Created using the Commons-io library

Let`s see with an example.

Create a file using the File class

You can create a file using File.createNewFile(). Returns a boolean indicating whether the file was created.

try {
    File file = new File("/home/js/test/text.txt");
    boolean success = file.createNewFile();
    if (!success) {
        System.out.println("Failed to create a file : /home/js/test/text.txt");
    }
} catch (IOException e) {
    e.printStackTrace();
}

If the file already exists, the file creation fails and false is returned.

Create using Path and Files (Java7)

You can create a file using the Path and Files of the Java7 nio package.

The following example creates a file.

try {
    Path filePath = Paths.get("/home/js/test/text.txt");
    Files.createFile(filePath);
} catch (IOException e) {
    e.printStackTrace();
}

If there is a directory that does not exist in the file path, an exception is raised and the file creation fails.

For example, when the code below is executed, if the folder /home/js/test/new_dir/ does not exist, an exception is thrown and the file cannot be created.

try {
    Path filePath = Paths.get("/home/js/test/new_dir/text.txt");
    Files.createFile(filePath);
} catch (IOException e) {
    e.printStackTrace();
}

When I run the code, the following exception is thrown.

java.nio.file.NoSuchFileException: /home/js/test/new_dir/text.txt
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.createFile(Files.java:632)
at example.io.CreateFile.main(CreateFile.java:37)

So, in this case, you need to create the folder first and create the file.

Create file using Commons-io library

The Commons-io library provides the FileUtils class, with which you can create files.

Gradle project adds the following to dependencies of build.gradle.

dependencies {
  compile group: 'commons-io', name: 'commons-io', version: '2.6'
  ...
}

For projects that use other build systems such as Maven, refer to mvnrepository.com and configure it.

FileUtils.touch() creates the file passed as an argument.

try {
    File file = new File("/home/js/test/new_dir/text.txt");
    FileUtils.touch(file);
} catch (IOException e) {
    e.printStackTrace();
}

Unlike the Files class above, FileUtils.touch() creates a folder and creates a file if there is an uncreated folder in the file path.

So, even if /home/js/test/new_dir does not exist, it will not affect the creation of the file.

Reference

codechachaCopyright ©2019 codechacha