Java Create New File - Java @ Desk

Saturday, December 7, 2013

Java Create New File

Java Create New File

To create a new file in java, following package is getting used
1) import - To handle file operations
2) import - To handle any exceptions occur during the file operation

While creating a file, following things need to be checked:
1) The file to be created, exists or not. It can be checked using the exists() method
2) If the above condition return false, the method createNewFile() is called.
 package test;  
 public class FileCreate {  
      public static void main(String[] args) throws IOException {  
           File file = new File("D:\\kumar\\Blogs\\File Operations\\newfile.txt");  
           if (file.exists()) {  
                System.out.println("File already exists");  
           } else {  
                System.out.println("File is created!");  

As mentioned in the code, if exists() method return false we go ahead with the file creation
At first execution the output will be "File is created!"
After first execution, output will be "File already exists"

No comments:

Post a Comment