In this tutorial, I am attaching the simple program about, How to create a file in Java. The program has been tested and output were shared in the post.

In order to create a file using Java, We have to invoke the predefined method called createNewFile(). Which is belongs to java.io.File class. This method will return boolean. value such as true if the file is created successfully or else false if the file is already exist in the file system.

FileCreationExample.java

package com.dineshkrish.files;
import java.io.File;
import java.io.IOException;
public class FileCreationExample {
public static void main(String[] args) {
// Defining File Object 
File file = new File("abc.txt"); // you can change path accordingly ie: c://xyz.txt
boolean status = false;
try {
// method to create new file in file system
status = file.createNewFile();
if(status) {
System.out.println("The File is Created Sucessfully!!!");
} else {
System.out.println("The File is already exist.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Reference

1. Java API Documentation

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *