Create New File in JAVA

How to create a new file in Java?

We have different  ways to create a new File in JAVA.

  1. Create a new file using java.io.File

  2. Using FIleUtils class of Apache Commons IO

1) Create a new file using java.io.File

File class has a method createNewFile() will be used to create  a new file in java.

If we call this method with existing file, the createNewFile will return false.

import java.io.File;
import java.io.IOException;
 
public class CreateNewFileExample {
    
    public static void main(String[] args) throws IOException{
        
        File file = new File("E:/java/example.txt");
        
        boolean isCreated = file.createNewFile();
        
        System.out.println("File created? " + isCreated);
    }
}

Output

File created? true 

 If we execute above program with same file name then the out will be

File created? false 

 

java.io.IOException

In the above example we created file at E:/java directory. If the Directory not exist it will return exception

Exception in thread "main" java.io.IOException: The system cannot find the path specified
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:1012)
    at javaapplication1.CreateNewFileExample.main(CreateNewFileExample.java:17)
Java Result: 1

 

2) Using FIleUtils class of Apache Commons IO

public static void main(String[] args) throws IOException{    

    File file = new File("E:/java/example.txt");        

    FileUtils.touch(file);

}

The touch method has the same behavior as the Unix touch command. If the file already exist, it modifies the file’s timestamp. If the file does not exist, it creates it along with the required parent directories