SCJP Study Guide:
API Contents


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
XyzWs Study Guide: SCJP: File

File


Purpose


The java.io.File class represents a file or a directory and defines a number of important methods for manipulating files and directories. Use the File class for typical operations such as creating, deleting, searching, and renaming files and directories; manuplating file's attributes; checking whether file exist, and so on.

The File class does not actually provide for read/write to files. It simply provides an identifier of files and directories.

When a File object is created, it does not mean that a file or directory with the identifier held by that File object actually exists on the disk; you must call exists() to check whether .

Constructors of File Class

The File class includes several overloaded constructors:

File(File parent, String child) Creates a new File instance from a parent abstract pathname and a child pathname string.The parent File object represents a directory.
File(String pathname) Creates a new File instance by converting the given pathname string into an abstract pathname.
File(String parent,String child) Creates a new File instance from a parent pathname string and a child pathname string.
File(URI uri) Creates a new File instance by converting the given file: URI into an abstract pathname.

For example,

1) Create a File object refers to a file named  myTest.txt in the current directory of the program that the JVM is running:

 
    File f = new File("myTest.txt");
    if (f.exists()) {
      try { 
        FileReader fr = new FileReader(f);
        fr.read();
        ...
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else { ... }

The file myTest.txt may or may not exist in the current directory. You must use exits() method to determine whether file exists before you use File object that refers to a file for reading and writing operations, otherwise an FileNotFoundException exception will be thrown. In the above example, we checked file existing status before we read it.

2) Create a File object refers to a file named  myTest.txt in the c:\testDir directory:

   File f = new File("c:\\testDir", "myTest.txt");
     if (f.exists()) {
       ;
     } else {
       try {
         f.createNewFile();
         FileWriter fr = new FileWriter(f);
         ....
       } catch (IOException e) {
         e.printStackTrace();
       }
     }

The exists method returns false that means the c:\testDir\myTest.txt did not exist now but it does not have any additional information about whether the directory existed. If the directory does not exist on the specified storage, when you try to call createNewFile method it will throw an IOException exception.

3) Create a File object refers to a file named  myTest.txt in the c:\testDir directory by using another way.

    File dir = new File("c:\\testFile"); 
    dir.mkdir(); //Create a directory
    File f = new File(dir, "myTest.txt");
    if (f.exists()) { 
	  ;
    }
    else {
      try {
        f.createNewFile();
        FileWriter fr = new FileWriter(f);
        ...
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

Useful Methods

 boolean canRead() Tests whether the application can read the file denoted by this abstract pathname. Returns true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise
 boolean canWrite() Tests whether the application can modify the file denoted by this abstract pathname. Returns true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
 int compareTo(File pathname) Compares two abstract pathnames lexicographically.
 boolean createNewFile() Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. May throw IOException if an I/O error occurred. Return true if the named file does not exist and was successfully created; false if the named file already exists
static File createTempFile(String prefix, String suffix)

Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. May throw an IllegalArgumentException if the prefix argument contains fewer than three characters and an IOException if a file could not be created.

The prefix string to be used in generating the file's name; must be at least three characters long. The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used.

static File createTempFile(String prefix, String suffix, File directory)

Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. May throw an IllegalArgumentException if the prefix argument contains fewer than three characters and an IOException if a file could not be created.

The prefix string to be used in generating the file's name; must be at least three characters long. The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used. The directory in which the file is to be created, or null if the default temporary-file directory is to be used.

 boolean delete()

Deletes the file or directory denoted by this abstract pathname. true if and only if the file or directory is successfully deleted; false otherwise.

If this pathname denotes a directory, then the directory must be empty in order to be deleted.  

 void deleteOnExit()

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

Once deletion has been requested, it is not possible to cancel the request. This method should therefore be used with care.

 boolean equals(Object obj) Tests this abstract pathname for equality with the given object.
 boolean exists() Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise.
 File getAbsoluteFile() Returns the absolute form of this abstract pathname. The absolute abstract pathname denoting the same file or directory as this abstract pathname.
 String getAbsolutePath() Returns the absolute pathname string of this abstract pathname.
 File getCanonicalFile() Returns the canonical form of this abstract pathname.
 String getCanonicalPath() Returns the canonical pathname string of this abstract pathname.
 String getName() Returns the name of the file or directory denoted by this abstract pathname. This is just the last name in the pathname's name sequence. If the pathname's name sequence is empty, then the empty string is returned. The path information is not returned. 
 String getParent() Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
 File getParentFile() Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.
 String getPath() Converts this abstract pathname into a pathname string.
 int hashCode() Computes a hash code for this abstract pathname.
 boolean isAbsolute() Tests whether this abstract pathname is absolute.
 boolean isDirectory() Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise.
 boolean isFile() Tests whether the file denoted by this abstract pathname is a normal file. Returns true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise.
 boolean isHidden() Tests whether the file named by this abstract pathname is a hidden file. Returns true if and only if the file denoted by this abstract pathname is hidden according to the conventions of the underlying platform.
 long lastModified() Returns the time that the file denoted by this abstract pathname was last modified.
 long length() Returns the length of the file denoted by this abstract pathname.
 String[] list()

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

Returns An array of strings naming the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty.

Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

 String[] list(FilenameFilter filter) Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
 File[] listFiles()

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

If this abstract pathname does not denote a directory, or an I/O error occurs, then this method returns null. Otherwise an array of File objects is returned, one for each file or directory in the directory. Pathnames denoting the directory itself and the directory's parent directory are not included in the result.

The array will be empty if the directory is empty.

 File[] listFiles(FileFilter filter) Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
 File[] listFiles(FilenameFilter filter) Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
static File[] listRoots() List the available filesystem roots.
 boolean mkdir() Creates the directory named by this abstract pathname. Returns true if and only if the directory was created; false otherwise.
 boolean mkdirs() Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Returns true if and only if the directory was created, along with all necessary parent directories; false otherwise.
 boolean renameTo(File dest) Renames the file denoted by this abstract pathname. Returns true if and only if the renaming succeeded; false otherwise. May throw an NullPointerException if parameter dest is null.
 boolean setLastModified(long time) Sets the last-modified time of the file or directory named by this abstract pathname. Returns true if and only if the operation succeeded; false otherwise. May throw an IllegalArgumentException if the argument is negative.
 boolean setReadOnly()

Marks the file or directory named by this abstract pathname so that only read operations are allowed. Returns true if and only if the operation succeeded; false otherwise.

After invoking this method the file or directory is guaranteed not to change until it is either deleted or marked to allow write access. Whether or not a read-only file or directory may be deleted depends upon the underlying system.

 String toString() Returns the pathname string of this abstract pathname.
 URI toURI() Constructs a file: URI that represents this abstract pathname.
 URL toURL() Converts this abstract pathname into a file: URL.

Examples:

1) List all files in a directory

public static void main(String[] args) {
    File directory = new File( "c:\\" );
    String[] listing = directory.list();
      
    for (String f: listing) {
      System.out.println( f );
    }
}

2) Get File Information

   public static void main( String args[] ) throws IOException {
      File exam = new File( "myTest.txt" );
      System.out.println( "Absolute Path: " + exam.getAbsolutePath()  );
      System.out.println( "Path: " + exam.getPath()  );
      System.out.println( "Name: " + exam.getName()  );
      System.out.println( "Parent: " + exam.getParent()  );
      System.out.println( "Can read: " + exam.canRead()  );
      System.out.println( "Can write: " + exam.canWrite()  );
      System.out.println( "Length: " + exam.length()  );
      System.out.println( "Modified?: " + exam.lastModified()  );
      System.out.println( "Modified!: " + new Date(exam.lastModified())  );
   }

3) Create a Temp file

   public static void main( String args[] ) throws IOException {
       // Create a temporary file to use during processing (Java 1.2 and later)
       File temp = File.createTempFile("app", ".tmp");  // Filename prefix and suffix
       // Make sure file gets deleted when we're done with it (Java 1.2 and later)
       temp.deleteOnExit();
   }

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |