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
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; |
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 |
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