beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to create a File in Java

By Chaitanya Singh | Filed Under: Java I/O

In this tutorial we will see how to create a file in Java using createNewFile() method. This method creates an empty file, if the file doesn’t exist at the specified location and returns true. If the file is already present then this method returns false. It throws:

IOException – If an Input/Output error occurs during file creation.
SecurityException – If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the file.

Complete code:
The below code would create a txt file named “newfile.txt” in C drive. You can change the path in the below code in order to create the file in different directory or in different drive.

package beginnersbook.com;
import java.io.File;
import java.io.IOException;

public class CreateFileDemo
{
   public static void main( String[] args )
   {	
      try {
	     File file = new File("C:\\newfile.txt");
	     /*If file gets created then the createNewFile() 
	      * method would return true or if the file is 
	      * already present it would return false
	      */
             boolean fvar = file.createNewFile();
	     if (fvar){
	          System.out.println("File has been created successfully");
	     }
	     else{
	          System.out.println("File already present at the specified location");
	     }
    	} catch (IOException e) {
    		System.out.println("Exception Occurred:");
	        e.printStackTrace();
	  }
   }
}

Reference:

Javadoc: createNewFile()

Enjoyed this post? Try these related posts

  1. How to write to a file in java using FileOutputStream
  2. Java – Find files with given extension
  3. How to Compress a File in GZIP Format
  4. How to read file in Java using BufferedReader
  5. How to get the last modified date of a file in java
  6. How to Copy a File to another File in Java

Comments

  1. Srivathsa b s says

    February 2, 2015 at 12:09 PM

    Do we have to download any jar files ??

    Reply
  2. siti says

    June 10, 2015 at 12:38 AM

    hi, is it possible to create a file within an android app using this code by changing the location?

    Reply

Leave a Reply Cancel reply

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

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap