File class

 

 

 File resides in the java.io package and a File object is immutable.

 

 Some things you can do with File's methods:

Delete files with the delete( ) method.

Delete an  empty directory.  If the directory was not empty it takes no action and returns false.

Compare path or file names

Extract the file name from a full pathname – getName( )

Obtain a file’s time last modified

List the filenames in a directory - list( )  Returns a String array of the names.

Create a new file - createNewFile( )   No action and returns false if file already exists.

Rename a file - renameTo(File obj)

Set a file to read only – setReadOnly( )

Create a new directory – mkdir( )

Create a new directory with necessary higher level parent directories– mkdirs( )

Change a filepathname to a URL

Test for presence of a directory - isDirectory( ),  or a regular file  -  isFile( )

Check if you can read or write to a file, without actually doing so and without  throwing an exception

 

  Things you CAN’T do with File:

 

                  You can't change the current directory with File.  You can get the current directory with:

 

String currentdir = System.getProperty("user.dir");

 

                  You can't rename a directory

 

                  You can't set a file to write access if it is Read Only

 

  In Windows, each directory in a File constructor requires double backslashes.  i.e.

 

File f = new File("c:\\test");

        and

File f = new File("c:\\test\\subtest");

 

  The filepathname can be two parts, separated by a comma.  i.e.

 

File f = new File("c:", "\test\\subtest\\brandnewfile.htm");            for Windows

File f = new File(“/”, “autoexec.bat”);                                  for Unix

 

 

to create a new file or directory

 

 For a new empty file:

 

import java.io.*;

 

File f = new File( "testfile.txt" );

try { f.createNewFile( ); }

catch (IOException ex)                { System.out.println( "File creation error." ); }

if (f.exists( )) { System.out.println( "File " + f.getName( ) + " created OK." ); } 

 

 For a new empty directory:

 

import java.io.*;

 

File f = new File( "c:\\testdirectory" );

try { f.mkdir( ); }

catch (Exception ex)                { System.out.println( "Dir creation error." ); }

if (f.exists( )) { System.out.println( "Dir  " + f.getName( ) + " created OK." ); }

 

 

to write over an existing file

 

File file = new File("c:\\111\\test.txt");

                                // at this point you simply don't do a file.createNewFile( );

                                PrintWriter pw = null;

                                try

                                {

                                                pw = new PrintWriter( new FileOutputStream(file), true);

                                                pw.println("Ode to a Lamb");

                                                pw.println(" ");

                                                pw.println("Mary had a little lamb.");

                                                pw.println("Its fleece was white as snow.");

                                                pw.println("And everywhere that Mary went");

                                                pw.println("Her lamb was sure to go.");

                                                System.out.println("All records written");

                                }

                                catch (IOException ex)

                                {

                                                System.out.println(" IOException!");

                                }

                                                                finally

                                {

                                                // won't write records if you don't close it

                                                if (pw != null) pw.close( );

                                }

 

 

to delete an existing file or directory

 

 The .delete( ) method below works for deleting directories too, but directories must be emptied beforehand.

 

import java.io.*;

 

// for a file

File f = new File( "testfile.txt" );

try { f.delete( ); }

catch (Exception ex)                { System.out.println( "File deletion error." ); }

if (!f.exists( )) { System.out.println( "File  " + f.getName( ) + " deleted OK." ); }

 

 

import java.io.*;

 

// for a directory

File f = new File( "c:\\mytestdirectory" );

try { f.delete( ); }

catch (Exception ex)                { System.out.println( "Dir deletion error." ); }

if (!f.exists( )) { System.out.println( "Dir  " + f.getName( ) + " deleted OK." ); }

 

 

to list files in a directory

 

  .list( ) and .listFiles( )

 

Returns an Array of filenames – a String[ ] array for list( ) and a File[ ] array for listFiles( )  i.e.

 

File f = new File("c:\\test"); File[ ] array = f.listFiles( );   

or

File f = new File("c:\\test"); String[ ] array = f.list( );

 

Filenames are relative if the pathname was relative, or absolute if the pathname was absolute.

 

Get the number of files with System.out.println(array.length);  or  System.out.println(java.lang.reflect.Array.getLength(array));

 

This snippet prints a directory’s file names:

 

import java.io.*;

import java.util.*;

 

File f = new File("c:\\tempdir");

String s[ ] = f.list( );

System.out.println( Arrays.asList( s ));

 

 

to determine if a file exists 

 

 ■  .exists( )

Returns true if a file in a File object filepathname exists. Else it returns false.  i.e. where  f  is a pre-existing File object here:

if(f.exists( ))  System.out.println(f + " exists! ");

 

 

to find the length of a file

 

   .length( )

 

Returns a long character length of a file in a File filepathname.  i.e.

 

long l = fileObject.length( );

 

 

to rename a file

 

 .renameTo( File )

 

Assuming f1 exists here:

 

import java.io.*;

 

File f1 = new File( "test.txt" );

File f2 = new File( "test1234.txt" );

try {

if (!f1.renameTo(f2)) System.out.println("File rename error"); }

catch (Exception ex) { System.out.println( "File rename exception." ); }

 

 

  .canRead( ) and .canWrite( )

 

Return true if the current program can read from or can write to a file in a File filepathname. False if not, or false if file doesn’t exist.

 

 

  .createNewFile( )

 

Creates the file named in the File object filepathname and returns true if successful.

The new file is empty with a .length( ) of zero

Throws checked IOException so .createNewFile( ) must go in a try-catch block

 

 

  .isFile( )  and  .isDirectory( )

 

Returns true if filepathname represents a file or a directory.

 

 

 

  .listRoots( )

 

Returns a File[ ] array of the Windows drives.  i.e.

 

File[ ] array = new File[0]; 

array = java.io.File.listRoots( );