// File: FileTest.java (Fig. 15.16 in JHTP2) // Demonstrating the File class. import java.awt.*; import java.awt.event.*; import java.io.*; import com.deitel.jhtp2.ch11.CloseWindowAndExit; public class FileTest extends Frame implements ActionListener { private TextField enter; private TextArea output; public FileTest() { super( "Testing class File" ); enter = new TextField( "Enter file or directory name here" ); enter.addActionListener( this ); output = new TextArea(); add( enter, BorderLayout.NORTH ); add( output, BorderLayout.CENTER ); setSize( 400, 400 ); setVisible( true ); } public void actionPerformed( ActionEvent e ) { File name = new File( e.getActionCommand() ); if ( name.exists() ) { output.setText( name.getName() + " exists\n" + ( name.isFile() ? "is a file\n" : "is not a file\n" ) + ( name.isDirectory() ? "is a directory\n" : "is not a directory\n" ) + ( name.isAbsolute() ? "is absolute path\n" : "is not absolute path\n" ) + "Last modified: " + name.lastModified() + "\nLength: " + name.length() + "\nPath: " + name.getPath() + "\nAbsolute path: " + name.getAbsolutePath() + "\nParent: " + name.getParent() ); if ( name.isFile() ) { try { RandomAccessFile r = new RandomAccessFile( name, "r" ); StringBuffer buf = new StringBuffer(); String text; output.append( "\n\n" ); while( ( text = r.readLine() ) != null ) buf.append( text + "\n" ); output.append( buf.toString() ); } catch( IOException e2 ) { } } else if ( name.isDirectory() ) { String directory[] = name.list(); output.append( "\n\nDirectory contents:\n"); for ( int i = 0; i < directory.length; i++ ) output.append( directory[ i ] + "\n" ); } } else { output.setText( e.getActionCommand() + " does not exist\n" ); } } public static void main( String args[] ) { FileTest f = new FileTest(); f.addWindowListener( new CloseWindowAndExit() ); } }