Programming and Problem Solving with Java

(やまだぃちぅ) #1
5.1 File Input and Output | 217

following method call first writes its argument to the file payFile, and then writes an EOL mark
to start a new line in the file:


payFile.println("Rate = "+ rate);


Now we turn our attention to file input. The BufferedReaderclass provides the readLine
method with which we’re already familiar from reading lines entered via System.in. Recall
that readLineis a value-returning method that returns the input line as a string. This method
actually reads the EOL mark at the end of the line, but then discards it instead of storing it
in the string. As a consequence, the file pointer advances to the start of the next line. If we
read a line from one file, we can write it out to another file with println. For example, if
dataLineis a Stringobject, we can write


dataLine = dataFile.readLine();
payFile.println(dataLine);


When printlnoutputs the string in dataLine, it appends an EOL mark that replaces the
one discarded by readLine. The advantage of having readLinediscard the EOL mark is that it
is easier to work with the input string. For example, if we want to add some characters to the
end of the string before we write it to payFile, we can simply use string concatenation:


dataLine = dataFile.readLine();
dataLine = dataLine + "***";
payFile.println(dataLine);


If readLinedid notdiscard the EOL mark, then after the concatenation an EOL mark would
appear between the last character from the input line and the appended stars. The call to
printlnwould then output two lines on payFile.
What happens when we call readLineand the file pointer is at EOF? At EOF, there’s no valid
value to return as a string. Java defines a special value called nullthat signifies that a refer-
ence type variable contains an invalid value. When readLinediscovers that the file pointer
is already at EOF, it returns the value null. Note that nullis not the same as the empty string.
Rather, it is a unique value in Java that does not correspond to any valid object value. We will
see later how we can test for nullin a Boolean expression.
If readLinealways returns a string, how do we get numbers into our application? Exactly
the same way we did with System.in. We must convert the string to a numeric value using
one of the parsemethods. As a reminder, here is how we have been getting a floating-point
value from System.in:


doublenumber;
number = Double.parseDouble(in.readLine());


Using this code as a model, we can input a floating-point value from a file as follows:


doublefloatNumber;
floatNumber = Double.parseDouble(dataFile.readLine());

Free download pdf