Java Reference
In-Depth Information
separator, which is the same as on UNIX. The statement new File("image/us.gif")
works on Windows, UNIX, and any other platform.
Listing 14.12 demonstrates how to create a File object and use the methods in the File
class to obtain its properties. The program creates a File object for the file us.gif . This file is
stored under the image directory in the current directory.
L ISTING 14.12 TestFileClass.java
1 public class TestFileClass {
2
public static void main(String[] args) {
3
4 System.out.println( "Does it exist? " + );
5 System.out.println( "The file has " + file.length() + " bytes" );
6 System.out.println( "Can it be read? " + file.canRead());
7 System.out.println( "Can it be written? " + file.canWrite());
8 System.out.println( "Is it a directory? " + file.isDirectory());
9 System.out.println( "Is it a file? " + file.isFile());
10 System.out.println( "Is it absolute? " + file.isAbsolute());
11 System.out.println( "Is it hidden? " + file.isHidden());
12 System.out.println( "Absolute path is " +
13 file.getAbsolutePath());
14 System.out.println( "Last modified on " +
15
java.io.File file = new java.io.File( "image/us.gif" );
create a File object
exists()
length()
canRead()
canWrite()
isDirectory()
isFile()
isAbsolute()
isHidden()
file.exists()
getAbsolutePath()
new java.util.Date(file.lastModified()));
lastModified()
16 }
17 }
The lastModified() method returns the date and time when the file was last modified,
measured in milliseconds since the beginning of UNIX time (00:00:00 GMT, January 1,
1970). The Date class is used to display it in a readable format in lines 14-15.
Figure 14.7a shows a sample run of the program on Windows, and Figure 14.7b, a sample
run on UNIX. As shown in the figures, the path-naming conventions on Windows are differ-
ent from those on UNIX.
(a) On Windows
(b) On UNIX
F IGURE 14.7
The program creates a File object and displays file properties.
14.26 What is wrong about creating a File object using the following statement?
Check
Point
new File( "c:\book\test.dat" );
14.27 How do you check whether a file already exists? How do you delete a file? How do
you rename a file? Can you find the file size (the number of bytes) using the File
class? How do you create a directory?
 
Search WWH ::




Custom Search