How to create a file in Java

The File.createNewFile() method is used to create a file in Java, and return a boolean value : true if the file is created successful; false if the file is already exists or the operation failed.

package com.mkyong.file;
 
import java.io.File;
import java.io.IOException;
 
public class CreateFileExample 
{
    public static void main( String[] args )
    {	
    	try {
 
	      File file = new File("c:\\newfile.txt");
 
	      if (file.createNewFile()){
	        System.out.println("File is created!");
	      }else{
	        System.out.println("File already exists.");
	      }
 
    	} catch (IOException e) {
	      e.printStackTrace();
	}
    }
}

Reference

  1. http://java.sun.com/javase/6/docs/api/java/io/File.html
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Khair Ali Naqvi

    Ya Ali Madad A.S

  • http://javabyvikas.blogspot.com Vikas Shukla

    Great Post sir…I learned much more from here….Please visit also java programming by vikas

  • http://www.river2c.com IT and Non IT Jobs

    Very simple example for Java beginners.

  • owenbowen

    i get an error saying access denied

  • amit

    Must Read

  • amit

    Good Tutorial

  • http://www.slideshare.net/susandukw/italian-garden-mckinney-coupon-save-big ryan

    Hello mates, its fantastic article on the topic of cultureand
    entirely defined, keep it up all the time.

  • raghu

    showing command like do without try and catch

  • keren happuch

    “enter the file name to be created” i want write the prg for this? if anyone know pls help

  • ravi.s

    i’m great fan of your site

  • Racha Suman

    your doing very well for creating good JAVA Programmers by learning from ur Website sir,,,,,,,,
    i likes ur website a lot and as well as u….
    From Racha Suman, India

  • Tlhologelo

    The tutorials would be good with documentation/comments there is really no beginner who can grasp this stuff all at once.

  • ashish

    I want to know is this a static page or dynamically generated

  • Pingback: Java I/O Tutorials | J2EE Web Development Tutorials()