Wednesday, May 9, 2012

Create New File Example in Java

Java has provided java.io.file pacakge  to work with File.

To create a new file File.createNewFile( ) method is used.
This method returns a boolean value true if the file is created otherwise return false. If the mentioned file for the specified directory is already exist then the createNewFile() method returns the false otherwise the method creates the mentioned file and return true.
here is the example of creating New file in java 

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

public class CreateNewFileExample 
{
 public static void main(String[] args) 
 {
  new CreateNewFileExample().createFile();
 }
 public void createFile()
 {
  try {
    
        File file = new File("d:\\db\\fileTest\\newfile.txt");
  
        if (file.createNewFile())
        {
         System.out.println("File is created successfully!");
        }
        else
        {
         System.out.println("Cannot create file, file already exists.");
        }
      } 
  catch (IOException e)
  {
        e.printStackTrace();
  }
 }
}

No comments:

Post a Comment