Class File

This section presents class File, which is particularly useful for retrieving information about files or directories from disk. Objects of class File do not open files or provide any file-processing capabilities. However, File objects are used frequently with objects of other java.io classes to specify files or directories to manipulate.

Creating File Objects

Class File provides four constructors. The constructor

 public File( String name )

specifies the name of a file or directory to associate with the File object. The name can contain path information as well as a file or directory name. A file or directory's path specifies its location on disk. The path includes some or all of the directories leading to the file or directory. An absolute path contains all the directories, starting with the root directory, that lead to a specific file or directory. Every file or directory on a particular disk drive has the same root directory in its path. A relative path normally starts from the directory in which the application began executing, and is therefore a path that is "relative" to the current directory.

The constructor

 public File( String pathToName, String name )

uses argument pathToName (an absolute or relative path) to locate the file or directory specified by name.

The constructor

 public File( File directory, String name )

uses an existing File object directory (an absolute or relative path) to locate the file or directory specified by name. Figure 14.3 lists some common File methods. The complete list can be viewed at java.sun.com/j2se/5.0/docs/api/java/io/File.html.

Figure 14.3. File methods.

(This item is displayed on page 679 in the print version)

Method

Description

boolean canRead()

Returns true if a file is readable by the current application; false otherwise.

boolean canWrite()

Returns true if a file is writable by the current application; false otherwise.

boolean exists()

Returns TRue if the name specified as the argument to the File constructor is a file or directory in the specified path; false otherwise.

boolean isFile()

Returns true if the name specified as the argument to the File constructor is a file; false otherwise.

boolean isDirectory()

Returns true if the name specified as the argument to the File constructor is a directory; false otherwise.

boolean isAbsolute()

Returns TRue if the arguments specified to the File constructor indicate an absolute path to a file or directory; false otherwise.

String getAbsolutePath()

Returns a string with the absolute path of the file or directory.

String getName()

Returns a string with the name of the file or directory.

String getPath()

Returns a string with the path of the file or directory.

String getParent()

Returns a string with the parent directory of the file or directory (i.e., the directory in which the file or directory can be found).

long length()

Returns the length of the file, in bytes. If the File object represents a directory, 0 is returned.

long lastModified()

Returns a platform-dependent representation of the time at which the file or directory was last modified. The value returned is useful only for comparison with other values returned by this method.

String[] list()

Returns an array of strings representing the contents of a directory. Returns null if the File object does not represent a directory.

The constructor

 public File( URI uri )

uses the given URI object to locate the file. A Uniform Resource Identifier (URI) is a more general form of the Uniform Resource Locators (URLs) that are used to locate Web sites. For example, http://www.deitel.com/ is the URL for the Deitel & Associates' Web site. URIs for locating files vary across operating systems. On Windows platforms, the URI

 file:/C:/data.txt

identifies the file data.txt stored in the root directory of the C: drive. On UNIX/Linux platforms, the URI

 file:/home/student/data.txt

identifies the file data.txt stored in the home directory of the user student.

Error-Prevention Tip 14.1

Use File method isFile to determine whether a File object represents a file (not a directory) before attempting to open the file.

 

Demonstrating Class File

Figure 14.4Fig. 14.5 demonstrate class File. The application prompts the user to enter a file name or directory name, then outputs information about the file name or directory name input.

Figure 14.4. File class used to obtain file and directory information.

 1 // Fig. 14.4: FileDemonstration.java
 2 // Demonstrating the File class.
 3 import java.io.File;
 4
 5 public class FileDemonstration
 6 {
 7 // display information about file user specifies
 8 public void analyzePath( String path )
 9 {
10 // create File object based on user input
11 File name = new File( path );
12
13 if ( name.exists() ) // if name exists, output information about it
14 {
15 // display file (or directory) information
16 System.out.printf(
17 %s%s
%s
%s
%s
%s%s
%s%s
%s%s
%s%s
%s%s",
18 name.getName() " exists",
19 ( name.isFile() ? "is a file" : "is not a file" ),
20 ( name.isDirectory() ? "is a directory" :
21 "is not a directory" ),
22 ( name.isAbsolute() ? "is absolute path" :
23 "is not absolute path" ), "Last modified: ",
24 name.lastModified(), "Length: ", name.length(),
25 "Path: ", name.getPath(), "Absolute path: ",
26 name.getAbsolutePath(), "Parent: ", name.getParent() );
27
28 if ( name.isDirectory() ) // output directory listing
29 {
30 String directory[] = name.list();
31 System.out.println( "

Directory contents:
" );
32
33 for ( String directoryName : directory )
34 System.out.printf( "%s
", directoryName );
35 } // end else
36 } // end outer if
37 else // not file or directory, output error message
38 {
39 System.out.printf( "%s %s", path, "does not exist." );
40 } // end else
41 } // end method analyzePath
42 } // end class FileDemonstration

Figure 14.5. Testing class FileDemonstration.

(This item is displayed on page 681 in the print version)

 1 // Fig. 14.5: FileDemonstrationTest.java
 2 // Testing the FileDemonstration class.
 3 import java.util.Scanner;
 4
 5 public class FileDemonstrationTest
 6 {
 7 public static void main( String args[] )
 8 {
 9 Scanner input = new Scanner( System.in );
10 FileDemonstration application = new FileDemonstration();
11
12 System.out.print( "Enter file or directory name here: " );
13 application.analyzePath( input.nextLine() );
14 } // end main
15 } // end class FileDemonstrationTest
 
Enter file or directory name here: C:Program FilesJavajdk1.5.0demojfc
jfc exists
is not a file
is a directory
is absolute path
Last modified: 1083938776645
Length: 0
Path: C:Program FilesJavajdk1.5.0demojfc
Absolute path: C:Program FilesJavajdk1.5.0demojfc
Parent: C:Program FilesJavajdk1.5.0demo

Directory contents:

CodePointIM
FileChooserDemo
Font2DTest
Java2D
Metalworks
Notepad
SampleTree
Stylepad
SwingApplet
SwingSet2
TableExample
 
 
Enter file or directory name here:
C:Program FilesJavajdk1.5.0demojfcJava2D
eadme.txt
readme.txt exists
is a file
is not a directory
is absolute path
Last modified: 1083938778347
Length: 7501
Path: C:Program FilesJavajdk1.5.0demojfcJava2D
eadme.txt
Absolute path: C:Program FilesJavajdk1.5.0demojfcJava2D
eadme.txt
Parent: C:Program FilesJavajdk1.5.0demojfcJava2D
 

The program begins by prompting the user for a file or directory (line 12 of Fig. 14.5). Line 13 inputs the file name or directory name and passes it to method analyzePath (lines 841 of Fig. 14.4). The method creates a new File object (line 11) and assigns its reference to name. Line 13 invokes File method exists to determine whether the name input by the user exists (either as a file or as a directory) on the disk. If the name input by the user does not exist, control proceeds to lines 3740 and displays a message to the screen containing the name the user typed, followed by "does not exist." Otherwise, the body of the if statement (lines 1336) executes. The program outputs the name of the file or directory (line 18), followed by the results of testing the File object with isFile (line 19), isDirectory (line 20) and isAbsolute (line 22). Next, the program displays the values returned by lastModified (line 24), length (line 24), getPath (line 25), getAbsolutePath (line 26) and getParent (line 26). If the File object represents a directory (line 28), the program obtains a list of the directory's contents as an array of Strings by using File method list (line 30) and displays the list on the screen.

The first output of this program demonstrates a File object associated with the jfc directory from the Java 2 Software Development Kit. The second output demonstrates a File object associated with the readme.txt file from the Java 2D example that comes with the Java 2 Software Development Kit. In both cases, we specified an absolute path on our personal computer.

A separator character is used to separate directories and files in the path. On a Windows computer, the separator character is a backslash () character. On a UNIX workstation, it is a forward slash (/) character. Java processes both characters identically in a path name. For example, if we were to use the path

 c:Program FilesJavajdk1.5.0demo/jfc

which employs each separator character, Java still processes the path properly. When building strings that represent path information, use File.pathSeparator to obtain the local computer's proper separator character rather than explicitly using / or . This constant returns a String consisting of one characterthe proper separator for the system.

Common Programming Error 14.1

Using as a directory separator rather than \ in a string literal is a logic error. A single indicates that the followed by the next character represents an escape sequence. Use \ to insert a in a string literal.


Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

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