File Management

   


You have learned how to read and write data from a file. However, there is more to file management than reading and writing. The File class encapsulates the functionality that you will need in order to work with the file system on the user's machine. For example, you use the File class to find out when a file was last modified or to remove or rename the file. In other words, the stream classes are concerned with the contents of the file, whereas the File class is concerned with the storage of the file on a disk.

NOTE

As is so often the case in Java, the File class takes the least common denominator approach. For example, under Windows, you can find out (or set) the read-only flag for a file, but while you can find out if it is a hidden file, you can't hide it without using a native method (see Volume 2).


The simplest constructor for a File object takes a (full) file name. If you don't supply a path name, then Java uses the current directory. For example,

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

gives you a file object with this name in the current directory. (The "current directory" is the current directory of the process that executes the virtual machine. If you launched the virtual machine from the command line, it is the directory from which you started the java executable.)

A call to this constructor does not create a file with this name if it doesn't exist. Actually, creating a file from a File object is done with one of the stream class constructors or the createNewFile method in the File class. The createNewFile method only creates a file if no file with that name exists, and it returns a boolean to tell you whether it was successful.

On the other hand, once you have a File object, the exists method in the File class tells you whether a file exists with that name. For example, the following trial program would almost certainly print "false" on anyone's machine, and yet it can print out a path name to this nonexistent file.

 import java.io.*; public class Test {    public static void main(String args[])    {       File f = new File("afilethatprobablydoesntexist");       System.out.println(f.getAbsolutePath());       System.out.println(f.exists());    } } 

There are two other constructors for File objects:

 File(String path, String name) 

which creates a File object with the given name in the directory specified by the path parameter. (If the path parameter is null, this constructor creates a File object, using the current directory.)

Finally, you can use an existing File object in the constructor:

 File(File dir, String name) 

where the File object represents a directory and, as before, if dir is null, the constructor creates a File object in the current directory.

Somewhat confusingly, a File object can represent either a file or a directory (perhaps because the operating system that the Java designers were most familiar with happens to implement directories as files). You use the isDirectory and isFile methods to tell whether the file object represents a file or a directory. This is surprising in an object-oriented system, you might have expected a separate Directory class, perhaps extending the File class.

To make an object representing a directory, you simply supply the directory name in the File constructor:

 File tempDir = new File(File.separator + "temp"); 

If this directory does not yet exist, you can create it with the mkdir method:

 tempDir.mkdir(); 

If a file object represents a directory, use list() to get an array of the file names in that directory. The program in Example 12 7 uses all these methods to print out the directory substructure of whatever path is entered on the command line. (It would be easy enough to change this program into a utility class that returns a vector of the subdirectories for further processing.)

TIP

Always use File objects, not strings, when manipulating file or directory names. For example, the equals method of the File class knows that some file systems are not case significant and that a trailing / in a directory name doesn't matter.


Example 12-7. FindDirectories.java
  1. import java.io.*;  2.  3. public class FindDirectories  4. {  5.    public static void main(String[] args)  6.    {  7.       // if no arguments provided, start at the parent directory  8.       if (args.length == 0) args = new String[] { ".." };  9. 10.       try 11.       { 12.          File pathName = new File(args[0]); 13.          String[] fileNames = pathName.list(); 14. 15.          // enumerate all files in the directory 16.          for (int i = 0; i < fileNames.length; i++) 17.          { 18.             File f = new File(pathName.getPath(), fileNames[i]); 19. 20.             // if the file is again a directory, call the main method recursively 21.             if (f.isDirectory()) 22.             { 23.                System.out.println(f.getCanonicalPath()); 24.                main(new String [] { f.getPath() }); 25.             } 26.          } 27.       } 28.       catch(IOException e) 29.       { 30.          e.printStackTrace(); 31.       } 32.    } 33. } 

Rather than listing all files in a directory, you can use a FileNameFilter object as a parameter to the list method to narrow down the list. These objects are simply instances of a class that satisfies the FilenameFilter interface.

All a class needs to do to implement the FilenameFilter interface is define a method called accept. Here is an example of a simple FilenameFilter class that allows only files with a specified extension:

 public class ExtensionFilter implements FilenameFilter {    public ExtensionFilter(String ext)    {       extension = "." + ext;    }    public boolean accept(File dir, String name)    {       return name.endsWith(extension);    }    private String extension; } 

When writing portable programs, it is a challenge to specify file names with subdirectories. As we mentioned earlier, it turns out that you can use a forward slash (the UNIX separator) as the directory separator in Windows as well, but other operating systems might not permit this, so we don't recommend using a forward slash.

CAUTION

If you do use forward slashes as directory separators in Windows when constructing a File object, the getAbsolutePath method returns a file name that contains forward slashes, which will look strange to Windows users. Instead, use the getCanonicalPath method it replaces the forward slashes with backslashes.


It is much better to use the information about the current directory separator that the File class stores in a static instance field called separator. (In a Windows environment, this is a backslash (\); in a UNIX environment, it is a forward slash (/). For example:

 File foo = new File("Documents" + File.separator + "data.txt") 

Of course, if you use the second alternate version of the File constructor

 File foo = new File("Documents", "data.txt") 

then the constructor will supply the correct separator.

The API notes that follow give you what we think are the most important remaining methods of the File class; their use should be straightforward.


 java.io.File 1.0 

  • boolean canRead()

    indicates whether the file can be read by the current application.

  • boolean canWrite()

    indicates whether the file is writable or read-only.

  • static boolean createTempFile(String prefix, String suffix) 1.2

  • static boolean createTempFile(String prefix, String suffix, File directory) 1.2

    create a temporary file in the system's default temp directory or the given directory, using the given prefix and suffix to generate the temporary name.

    Parameters:

    prefix

    A prefix string that is at least three characters long

     

    suffix

    An optional suffix. If null, .tmp is used

     

    directory

    The directory in which the file is created. If it is null, the file is created in the current working directory


  • boolean delete()

    tries to delete the file. Returns true if the file was deleted, false otherwise.

  • void deleteOnExit()

    requests that the file be deleted when the virtual machine shuts down.

  • boolean exists()

    true if the file or directory exists; false otherwise.

  • String getAbsolutePath()

    returns a string that contains the absolute path name. Tip: Use getCanonicalPath instead.

  • File getCanonicalFile() 1.2

    returns a File object that contains the canonical path name for the file. In particular, redundant "." directories are removed, the correct directory separator is used, and the capitalization preferred by the underlying file system is obtained.

  • String getCanonicalPath() 1.1

    returns a string that contains the canonical path name. In particular, redundant "." directories are removed, the correct directory separator is used, and the capitalization preferred by the underlying file system is obtained.

  • String getName()

    returns a string that contains the file name of the File object (does not include path information).

  • String getParent()

    returns a string that contains the name of the parent of this File object. If this File object is a file, then the parent is the directory containing it. If it is a directory, then the parent is the parent directory or null if there is no parent directory.

  • File getParentFile() 1.2

    returns a File object for the parent of this File directory. See getParent for a definition of "parent."

  • String getPath()

    returns a string that contains the path name of the file.

  • boolean isDirectory()

    returns true if the File represents a directory; false otherwise.

  • boolean isFile()

    returns true if the File object represents a file as opposed to a directory or a device.

  • boolean isHidden() 1.2

    returns TRue if the File object represents a hidden file or directory.

  • long lastModified()

    returns the time the file was last modified (counted in milliseconds since Midnight January 1, 1970 GMT), or 0 if the file does not exist. Use the Date(long) constructor to convert this value to a date.

  • long length()

    returns the length of the file in bytes, or 0 if the file does not exist.

  • String[] list()

    returns an array of strings that contain the names of the files and directories contained by this File object, or null if this File was not representing a directory.

  • String[] list(FilenameFilter filter)

    returns an array of the names of the files and directories contained by this File that satisfy the filter, or null if none exist.

    Parameters:

    filter

    The FilenameFilter object to use


  • File[] listFiles() 1.2

    returns an array of File objects corresponding to the files and directories contained by this File object, or null if this File was not representing a directory.

  • File[] listFiles(FilenameFilter filter) 1.2

    returns an array of File objects for the files and directories contained by this File that satisfy the filter, or null if none exist.

    Parameters:

    filter

    The FilenameFilter object to use


  • static File[] listRoots() 1.2

    returns an array of File objects corresponding to all the available file roots. (For example, on a Windows system, you get the File objects representing the installed drives (both local drives and mapped network drives). On a UNIX system, you simply get "/".)

  • boolean createNewFile() 1.2

    automatically makes a new file whose name is given by the File object if no file with that name exists. That is, the checking for the file name and the creation are not interrupted by other file system activity. Returns true if the method created the file.

  • boolean mkdir()

    makes a subdirectory whose name is given by the File object. Returns TRue if the directory was successfully created; false otherwise.

  • boolean mkdirs()

    unlike mkdir, creates the parent directories if necessary. Returns false if any of the necessary directories could not be created.

  • boolean renameTo(File dest)

    returns true if the name was changed; false otherwise.

    Parameters:

    dest

    A File object that specifies the new name


  • boolean setLastModified(long time) 1.2

    sets the last modified time of the file. Returns true if successful, false otherwise.

    Parameters:

    time

    A long integer representing the number of milliseconds since Midnight January 1, 1970, GMT. Use the getTime method of the Date class to calculate this value


  • boolean setReadOnly() 1.2

    sets the file to be read-only. Returns TRue if successful, false otherwise.

  • URL toURL() 1.2

    converts the File object to a file URL.


 java.io.FilenameFilter 1.0 

  • boolean accept(File dir, String name)

    should be defined to return TRue if the file matches the filter criterion.

    Parameters:

    dir

    A File object representing the directory that contains the file

     

    name

    The name of the file



       
    top



    Core Java 2 Volume I - Fundamentals
    Core Java(TM) 2, Volume I--Fundamentals (7th Edition) (Core Series) (Core Series)
    ISBN: 0131482025
    EAN: 2147483647
    Year: 2003
    Pages: 132

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net