Files and I/O (Cont.)


Creating a File
Use the createNewFile() method to create a file in a specific directory (requires permission) by specifying the path of the file and use double backslashes to escape the "\" character (for Windows):
   File myObj = new File( "C:\\Users\\MyName\\filename.txt" );
On Mac and Linux you can just write the path, like: /users/name/filename.txt . This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):

CreateFile.java (creating a file)

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

 public class CreateFile {
   public static void main( String[ ] args ) {
     try {
       File myObj = new File( args[0] );
       if ( myObj.( ) )
         System.out.print( "File created: " + myObj.getName( ) );
       else
         System.out.print( "File already exists." );
     }
     catch( IOException e ) {
       System.out.print( "An error occurred." );
       e.printStackTrace( );
     }
   }
 }
shell> java CreateFile            




      Never argue with a fool, they will lower you to their level, and then beat you with experience.