Java Reference
In-Depth Information
}
catch
(Exception ex) {
System.out.println(
"Exception in main"
);
}
}
static void
method()
throws
Exception {
try
{
Circle c1 =
new
Circle(
1
);
c1.setRadius(
-1
);
System.out.println(c1.getRadius());
}
catch
(RuntimeException ex) {
System.out.println(
"RuntimeException in method()
");
}
catch
(Exception ex) {
System.out.println(
"Exception in method()"
);
throw
ex;
}
}
}
The
File
class contains the methods for obtaining the properties of a file/directory
and for renaming and deleting a file/directory.
Key
Point
Having learned exception handling, you are ready to step into file processing. Data stored in
the program are temporary; they are lost when the program terminates. To permanently store
the data created in a program, you need to save them in a file on a disk or other permanent
storage device. The file can then be transported and read later by other programs. Since data
are stored in files, this section introduces how to use the
File
class to obtain file/directory
properties, to delete and rename files/directories, and to create directories. The next section
introduces how to read/write data from/to text files.
Every file is placed in a directory in the file system. An
absolute file name
(or
full name
)
contains a file name with its complete path and drive letter. For example,
c:\book\Welcome.java
is the absolute file name for the file
Welcome.java
on the Windows
operating system. Here
c:\book
is referred to as the
directory path
for the file. Absolute file
names are machine dependent. On the UNIX platform, the absolute file name may be
/home/liang/book/Welcome.java
, where
/home/liang/book
is the directory path for the
file
Welcome.java
.
A
relative file name
is in relation to the current working directory. The complete direc-
tory path for a relative file name is omitted. For example,
Welcome.java
is a relative file
name. If the current working directory is
c:\book
, the absolute file name would be
c:\book\Welcome.java
.
The
File
class is intended to provide an abstraction that deals with most of the machine-
dependent complexities of files and path names in a machine-independent fashion. The
File
class contains the methods for obtaining file and directory properties and for renaming and
deleting files and directories, as shown in Figure 14.6. However,
the
File
class does not con-
tain the methods for reading and writing file contents
.
The file name is a string. The
File
class is a wrapper class for the file name and its direc-
tory path. For example,
new File("c:\\book")
creates a
File
object for the directory
c:\book
, and
new File("c:\\book\\test.dat")
creates a
File
object for the file
c:\book\test.dat
, both on Windows. You can use the
File
class's
isDirectory()
method
to check whether the object represents a directory, and the
isFile()
method to check
whether the object represents a file.
why file?
absolute file name
directory path
relative file name