How to create empty file if it doesn’t exist

package JavaIOExample;

import java.io.File;
import java.io.IOException;

/*
 * Here we will learn to create new empty file
 */
public class CreateNewEmptyFiles {

	public static void main(String args[]) throws IOException {
		// Here we are assuming that folder "D:\Gautam\testing\" exists and
		// user has privilege to create file in testing folder
		File file = new File("D:\JBT\testing\first.txt");

		boolean b = false;

		/*
		 * exists() method tests whether the file or directory denoted by this
		 * abstract pathname exists or not accordingly it will return TRUE /
		 * FALSE.
		 */

		if (!file.exists()) {

			/*
			 * createNewFile() method is used to creates a new, empty file
			 * mentioned by given abstract pathname if and only if a file with
			 * this name does not exist in given abstract pathname.
			 */
			b = file.createNewFile();
		}

		if (b)
			System.out.println("Empty File successfully created");
		else
			System.out.println("Failed to create File");

	}
}

 

By | 2012-09-21T19:37:24+00:00 September 21st, 2012|Code Base|0 Comments

About the Author:

Leave A Comment