Creating Files

   

If you need to obtain information about a file, you should create an object of Java's File class. This class enables you to query the system about everything from the file's name to the time it was last modified. You can also use the File class to make new directories, as well as to delete and rename files. Create a File object by calling one of the class's three constructors, whose signatures are as follows :

 File(String path) File(String path, String name) File(File dir, String name) 

The first constructor creates a File object from the given full pathname (for example, C:\CLASSES\MYAPP.JAVA ). The second constructor creates the object from a separate path and a file. The third creates the object from a separate path and filename, with the path being associated with another File object.

The File class features a full set of methods that gives your program a lot of file-handling options. Table 21.4 lists these methods along with their descriptions. The parameters are not shown here in this listing. In some cases, there is more than one version of a method with the same name. The difference is the number and type of arguments the each version expects. Check the JavaDocs for the exact arguments expected by the method.

Table 21.4. Methods of the File Class
Method Description
getName() Gets the file's name (as a String ).
getPath() Gets the file's path (as a String ).
getAbsolutePath() Gets the file's absolute path (as a String ).
getAbsoluteFile() Gets the file's absolute path (as a File ).
getCanonicalPath() Gets the file's canonical path (as a String ).
getCanonicalFile() Gets the file's canonical path (as a File ).
getParent() Gets the file's parent directory (as a String ).
getParentFile () Gets the file's parent directory (as a File ).
exists () Returns true if the file exists, false otherwise .
createNewFile() Creates a new file, but only if the file does not already exist (returns true if the file was created).
createTempFile() Creates a temporary file. The file's name is created first, by name ( String pattern, the directory, and then by using the pattern to create a unique File directory) (returns a File ).
deleteOnExit() Requests that this file be deleted when the VM exits.
canWrite () Returns true if the file can be written to.
canRead () Returns true if the file can be read.
setReadOnly() Sets the file so that it is read-only.
isFile () Returns true if the file is valid.
isDirectory () Returns true if the directory is valid.
isAbsolute () Returns true if the filename is absolute.
isHidden() Tests to see if the file is hidden. (Returns true if it is.)
lastModified () Returns the time the file was last changed, represented as the number of milliseconds since 00:00:00 GMT, January 1, 1970.
setLastModified() Sets the time when the file was last modified. The time should be represented as the number of milliseconds since 00:00:00 GMT, January 1, 1970.
length () Returns the number of bytes in the file.
mkdir () Makes a directory represented by this file. (Returns true if successful.)
mkdirs () Makes a directory represented by this file, and any required but nonexistent parent directories.(Returns true if successful.)
renameTo(File dest) Renames the file to the indicated file.
list () Gets a list of files in the directory. (Returns an array of strings.)
listFiles () Gets a list of files in the directory. (Returns an array of files.)
listRoots() Gets a list of the root directories for the current system. A Windows or Macintosh computer would have one root for each drive; a Unix machine has one root (/). (Returned as an array of files.)
delete () Deletes the file. (Returns true if successful.)
hashCode () Gets a hash code for the file.
equals () Compares the file object with another object. (Returns true if they are equal.)
toString () Gets a string containing the file's path.
toURL() Returns an URL object equivalent to the file.

Note

This is only successful when the Virtual Machine exits normally, not by abnormal exits.


Troubleshooting Tip

If you are having trouble with the File class. See "Understanding the Use of the File Class" in the "Troubleshooting" section at the end of the chapter.


Creating Temporary Files

Temporary files are useful for a variety of purposes in many programs. To create a temporary file, you can use the static createTemporaryFile method in the File class. In Listing 21.5, a temporary file is created by passing in the name of the prefix and suffix of the file that you want to create. The string should contain the first several letters of the filename (minimum three characters ), followed by an extension. The VM will insert a four- or five-digit number that is guaranteed to be unique within this instance of the VM. If you do not provide an extension, it is automatically assigned the value of .tmp. You have to put the "." in the suffix for it to be added as an extension.

Listing 21.5 Source Code for CreateTempFile.java
 import java.io.*; public class CreateTempFile {     public static void main(String args[])     {         try         {           File tempFile = File.createTempFile( "myfile", ".tmp" );           FileOutputStream fout = new FileOutputStream(tempFile);           PrintStream out = new PrintStream(fout);           out.println("Place this test string in the temp file");         }         catch ( IOException ex )         {           System.out.println("There was a problem creating/writing to the temp file");           ex.printStackTrace();         }     } } 

After you run the CreateTempFile program in Listing 21.5, you should see a file called myfileXXXXX.tmp in your system's temp directory (where the X s are actually numbers ). There is also a constructor that will allow you to assign a directory location for the temporary file.

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

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