(^216) | File Objects and Looping Statements
As output proceeds, each successive output operation advances the file pointer to add data
to the end of the file.
Because calling the constructor creates a file object and prepares the file for reading or
writing, you must call it before you can use any input or output methods that refer to the file.
It’s a good habit to call the constructor early in the application to be sure that the files are
prepared before any attempts to perform file I/O are made.
public static voidmain(String[] args)
{
PrintWriter outFile;
BufferedReader inFile;
// Instantiate the file objects
outFile = new PrintWriter(new FileWriter("outfile.dat"));
inFile = new BufferedReader(new FileReader("infile.dat"));
.
.
.
}
Use Methods Associated with the File Object to Read or Write It Once a file has been declared and instan-
tiated, we are ready to use it. The main operation that we can perform on a file of the class
PrintWriteris to print a value onto it. The printmethod can be passed a value of any of Java’s
primitive types. We typically pass it a string, using string conversion to convert other types
such as intor doubleto be part of the string. For example:
outFile.print("The answer is " + 49);
We could also write
outFile.print("The answer is ");
outFile.print(49);
and the output would be identical to that produced by the preceding version. The intvalue
49 is converted to a string for output.
If you print a floating-point value that has been calculated within an application, you have
no control over the number of digits printed. For example, if you divide 1 by 3, you get
0.333333333 .... To gain control over the appearance of such numbers, you can use the String
class valueOfmethod, which takes a value of a numeric type as an argument and returns a
string representation of the value. Then you can use the Stringmethods indexOfand substring
to select only the characters representing the digits you wish to output. We ask you to ex-
plore this technique in the exercises at the end of this chapter.
PrintWriteralso provides a printlnmethod that works in the same way as the println
method associated with System.out. The only difference between printand printlnis that
printlnautomatically adds the EOL mark at the end of whatever it writes. For example, the