Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175

Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175

Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175
Writing a text file | Building Blocks Java

Writing a text file

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() use myOutput.println(). System.out and myOutput are just different instances of the PrintStream class. To print to a different PrintStream we keep the syntax the same but change the name of the PrintStream.
  • Comments are closed.