Files and I/O (Cont.)


Getting File Information
Now that we have created a file, we can use other File methods to get information about that file:

GetFileInfo.java (getting file information)

 import java.io.File;
 public class GetFileInfo {
   public static void main( String[ ] args ) {
     File myObj = new File( args[0] );
     if ( myObj.( ) ) {
       System.out.println( "File name: " + myObj.getName( ) );
       System.out.println( "Absolute path: " + myObj.getAbsolutePath( ) );
       System.out.println( "Writeable: " + myObj.canWrite( ) );
       System.out.println( "Readable: " + myObj.canRead( ) );
       System.out.println( "File size in bytes: " + myObj.length( ) );
     }
     else  System.out.println( "The file does not exist." );
   }
 }
shell> java GetFileInfo            

There are many available classes in the Java API that can be used to read and write files in Java. Which one to use depends on the Java version you are working with and whether you need to read bytes or characters, and the size of the file/lines, etc. Some of the file classes are given next: