The print and println methods can write to disk files. Here are some
examples:
During a run of the code in Listing 13-2, the variable total stores the
number 99.75. To deposit 99.75 into the cookedData.txt file, you execute
diskWriter.println(total);
This println call writes to a disk file because of the following line in
Listing 13-2:
PrintStream diskWriter =
new PrintStream(“cookedData.txt”);
In another version of the program, you may decide not to use a total
variable. To write 99.75 to the cookedData.txt file, you can call
diskWriter.println(unitPrice * quantity);
To display OK on the screen, you can make the following method call:
System.out.print(“OK”);
Chapter 13: Piles of Files: Dealing with Information Overload 227
To write OK to a file named approval.txt, you can use the following code:
PrintStream diskWriter =
new PrintStream(“approval.txt”);
diskWriter.print(“OK”);
You may decide to write OK as two separate characters. To write to the
screen, you can make the following calls:
System.out.print(‘O’);
System.out.print(‘K’);
And to write OK to the approval.txt file, you can use the following code:
PrintStream diskWriter =
new PrintStream(“approval.txt”);
diskWriter.print(‘O’);
diskWriter.print(‘K’);
Like their counterparts for System.out, the disk-writing print and
println methods differ in their end-of-line behaviors. For example, you
want to display the following text on the screen:
Hankees Socks
To do this, you can make the following method calls:
System.out.print(“Hankees “);
System.out.println(“Socks”);
System.out.print(7);
System.out.print(“ “);
System.out.println(3);
To plant the same text into a file named scores.dat, you can use the
following code:
PrintStream diskWriter =
new PrintStream(“scores.dat”);
diskWriter.print(“Hankees “);
diskWriter.println(“Socks”);
diskWriter.print(7);
diskWriter.print(“ “);
diskWriter.println(3);
No comments:
Post a Comment