How To Create a File in Java

This example will show you how to create a new file in Java.
To do this, we use the File.createNewFile() method.
The method returns a boolean value:
- true - The file has been successfully created.
- false - The operation failed or the file already exists.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package com.vertex.academy.file; /* * Vertex Academy * Java: a new file creation example */ import java.io.File; import java.io.IOException; public class CreateFileExample { public static void main( String[] args ) { try { File file = new File("c:\\project\\newfile.txt"); if (file.createNewFile()){ System.out.println("File ‘newfile.txt’ is created successfully!"); } else{ System.out.println("File ‘newfile.txt’ already exists."); } } catch (IOException e) { e.printStackTrace(); } } } |
Reference
http://docs.oracle.com/javase/8/docs/api/java/io/File.html