Writing a text file | Building Blocks Java (original) (raw)
Sometimes you want to save your output for posterity rather merely scrolling it across a screen. To do this we’ll need to learn how to write data to a file. rather than create a completely new program we’ll modify the Fahrenheit to Celsius conversion program to output to a file:
// Write the Fahrenheit to Celsius table in a file
import java.io.*;
class FahrToCelsius {
public static void main (String args[]) {
double fahr, celsius;
double lower, upper, step;
lower = 0.0; // lower limit of temperature table
upper = 300.0; // upper limit of temperature table
step = 20.0; // step size
fahr = lower;
try {
FileOutputStream fout = new FileOutputStream("test.out");
// now to the FileOutputStream into a PrintStream
PrintStream myOutput = new PrintStream(fout);
while (fahr <= upper) { // while loop begins here
celsius = 5.0 * (fahr-32.0) / 9.0;
myOutput.println(fahr + " " + celsius);
fahr = fahr + step;
} // while loop ends here
} // try ends here
catch (IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
} // main ends here
}
There are only three things necessary to write formatted output to a file rather than to the standard output:
- Open a FileOutputStream using a line like
FileOutputStream fout = new FileOutputStream("test.out");
This line initializes the FileOutputStream with the name of the file you want to write into.
- Convert the FileOutputStream into a PrintStream using a statement like
PrintStream myOutput = new PrintStream(fout);
The PrintStream is passed the FileOutputStream from step 1.
- Instead of using
System.out.println()
usemyOutput.println()
.System.out
andmyOutput
are just different instances of thePrintStream
class. To print to a differentPrintStream
we keep the syntax the same but change the name of thePrintStream
.
This entry was posted on Wednesday, July 29th, 2009 at 9:20 am and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.