Java Create File Sample Code

Creating a file in Java is pretty simple using the createNewFile() method of the Java File class. The code sample below will create a an empty file called SampleFileOut.txt in the specified folder. The sampleFileOut String contains the path to the sample file. You will need to change the path to correspond to your specific development environment.

All of the Java development I do is done using Eclipse IDE. Eclipse is super nice and I recommend you download and install it on your laptop/pc for doing all Java development. When you run this snippet of Java code using Eclipse or on the command line, it will create the empty file if it doesn’t already exist.

Java Create File Source Code:

package com.jcd.java.tutorials;

import java.io.File;
import java.lang.Exception;

public class JavaCreateFile 
{
	
	 public static void main( String[] args )
	 {
		String sampleFileOut = "C:\\Users\\Admin\\Documents\\SampleFileOut.txt";
		
		try 
		{
			File file = new File(sampleFileOut);
		
			boolean fileResult = file.createNewFile();
			
			if (fileResult)
			{
				System.out.println("File Created. Sweet!");
			}
			else
			{
				System.out.println("File Already Exists. Ooooof!");
			}
		}
		catch(Exception ex)
		{
			System.out.println("Exception:"+ex.toString());
		}
	}

}


Sample Java Create Output:

File Created. Sweet!



Sample Java Create Output: (file already existed)

File Already Exists. Ooooof!



Java References:

Add a Comment

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