Java Reference
In-Depth Information
file, starting with the directory that your program is in. The way that you specify path
names depends on your particular operating system.
A typical UNIX path name is
/user/sallyz/data/data.txt
To create a BufferedReader input stream connected to this file, use
BufferedReader inputStream =
new BufferedReader(
new FileReader("/user/sallyz/data/data.txt"));
Windows uses \ instead of / in path names. A typical Windows path name is
C:\dataFiles\goodData\data.txt
To create a BufferedReader input stream connected to this file, use
BufferedReader inputStream =
new BufferedReader(
new FileReader("C:\\dataFiles\\goodData\\data.txt"));
Note that you need to use \\ in place of \ , since otherwise Java will interpret a
backslash paired with a character, such as \d , as an escape character. Although you
must worry about using a backslash ( \ ) in a quoted string, this problem does not occur
with path names read in from the keyboard.
One way to avoid these escape character problems altogether is to always use
UNIX conventions when writing path names. A Java program will accept a path name
written in either Windows or UNIX format, even if it is run on a computer with an
operating system that does not match the syntax. Thus, an alternate way to create a
BufferedReader input stream connected to the Windows file
using \ ,
\\ , or /
C:\dataFiles\goodData\data.txt
is the following:
BufferedReader inputStream =
new BufferedReader(
new FileReader("C:/dataFiles/goodData/data.txt"));
Nested Constructor Invocations
Expressions with two constructors, such as the following, are common when dealing
with Java's library of I/O classes:
new BufferedReader( new FileReader("original.txt"))
This is a manifestation of the general approach to how Java I/O libraries work. Each
I/O class serves one or a small number of functions. To obtain full functionality, you
normally need to combine two (or more) class constructors. For example, in the previous
code, the object new FileReader("original.txt") establishes a connection with the
file original.txt but provides only very primitive methods for input. The constructor
for BufferedReader takes this file reader object and adds a richer collection of input
methods. In these cases, the inner object, such as new FileReader("original.txt") ,
is transformed into an instance variable of the outer object, such as BufferedReader .
 
Search WWH ::




Custom Search