1  // File: FileTest.java (Fig. 15.16 in JHTP2)
  2  // Demonstrating the File class.
  3  
  4  import java.awt.*;
  5  import java.awt.event.*;
  6  import java.io.*;
  7  import com.deitel.jhtp2.ch11.CloseWindowAndExit;
  8  
  9  public class FileTest extends Frame implements ActionListener {
 10  
 11     private TextField enter;
 12     private TextArea output;
 13  
 14     public FileTest()
 15     {
 16        super( "Testing class File" );
 17        enter = new TextField(
 18           "Enter file or directory name here" );
 19        enter.addActionListener( this );
 20        output = new TextArea();
 21        add( enter, BorderLayout.NORTH );
 22        add( output, BorderLayout.CENTER );
 23        setSize( 400, 400 );
 24        setVisible( true );
 25     }
 26  
 27     public void actionPerformed( ActionEvent e )
 28     {
 29        File name = new File( e.getActionCommand() );
 30  
 31        if ( name.exists() ) {
 32           output.setText(
 33              name.getName() + " exists\n" +
 34              ( name.isFile() ? "is a file\n" :
 35                                "is not a file\n" ) +
 36              ( name.isDirectory() ? "is a directory\n" :
 37                                     "is not a directory\n" ) +
 38              ( name.isAbsolute() ? "is absolute path\n" :
 39                                    "is not absolute path\n" ) +
 40              "Last modified: " + name.lastModified() +
 41              "\nLength: " + name.length() +
 42              "\nPath: " + name.getPath() +
 43              "\nAbsolute path: " + name.getAbsolutePath() +
 44              "\nParent: " + name.getParent() );
 45  
 46           if ( name.isFile() ) {
 47              try {
 48                 RandomAccessFile r =
 49                    new RandomAccessFile( name, "r" );
 50                 StringBuffer buf = new StringBuffer();
 51                 String text;
 52  
 53                 output.append( "\n\n" );
 54  
 55                 while( ( text = r.readLine() ) != null ) 
 56                    buf.append( text + "\n" );
 57  
 58                 output.append( buf.toString() );
 59              }
 60              catch( IOException e2 ) {
 61              }
 62           }
 63           else if ( name.isDirectory() ) {
 64              String directory[] = name.list();
 65  
 66              output.append( "\n\nDirectory contents:\n");
 67  
 68              for ( int i = 0; i < directory.length; i++ )
 69                 output.append( directory[ i ] + "\n" );
 70           }
 71        }
 72        else {
 73           output.setText( e.getActionCommand() +
 74                           " does not exist\n" );
 75        }       
 76     }
 77  
 78     public static void main( String args[] )
 79     {
 80        FileTest f = new FileTest();
 81        f.addWindowListener( new CloseWindowAndExit() );
 82     }
 83  }