Java Reference
In-Depth Information
Display 10.10
Redirecting Error Messages
(part 2 of 2)
Note the
stream
classes
used.
11
errStream =
12
new
PrintStream(
13
new
FileOutputStream("errormessages.txt"));
14
}
15
catch
(FileNotFoundException e)
16
{
17
System.out.println(
18
"Error opening file with FileOutputStream.");
19
System.exit(0);
20
}
21
System.setErr(errStream);
22
System.err.println("Hello from System.err.");
23
System.out.println("Hello from System.out.");
24
System.err.println("Hello again from System.err.");
None of
System.in
,
System.out
, or
System.err
needs to be closed, but the
streams you create should be explicitly
closed.
25
errStream.close();
26
}
27
}
F
ILE
errormessages.txt
Hello from System.err.
Hello again from System.err.
S
CREEN
O
UTPUT
Hello from System.out.
10.3
The
File
Class
The scars of others should teach us caution.
SAINT JEROME
In this section we describe the class
File
, which is not really an I/O stream class but is
often used in conjunction with file I/O. The class
File
is so important to file I/O pro-
gramming that it was even placed in the
java.io
package.
Programming with the
File
Class
The
File
class contains methods that allow you to check various properties of a file,
such whether there is a file with a specified name, whether the file can be written to,