Java Reference
In-Depth Information
is the same as on UNIX. The statement
new File("image/us.gif")
works on Windows,
UNIX, and any other platform.
Listing 12.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
12.12
TestFileClass.java
1
public class
TestFileClass {
2
public static void
main(String[] args) {
3 java.io.File file =
new
java.io.File(
"image/us.gif"
);
4 System.out.println(
"Does it exist? "
+ file.exists());
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
create a
File
exists()
length()
canRead()
canWrite()
isDirectory()
isFile()
isAbsolute()
isHidden()
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 12.7a shows a sample run of the program on Windows, and Figure 12.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
12.7
The program creates a
File
object and displays file properties.
12.27
What is wrong about creating a
File
object using the following statement?
new
File(
"c:\book\test.dat"
);
✓
✓
Check
Point
12.28
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?
12.29
Can you use the
File
class for I/O? Does creating a
File
object create a file on the disk?
Search WWH ::
Custom Search