How to create a file in Java

You can create a file in Java using File.createNewFile(path ..) Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. return a boolean value : true if the file creation successful; false if the file already exists or the operation failed.

Create New File – Java Snippet


 * @author Umashankar
public class CreateFile {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try {
			// file handle -> hold the path of the file
			File file = new File("c:\\newfile.txt");

			// file won't be created until, you call createNewFile()
			if (file.createNewFile()) {
				// running program for the first time, it would come here
				System.out.println("File created!");
			} else {
				// next time, would always come here as file is created.
				System.out.println("File already exists!");

		} catch (IOException e) {


Leave a Comment