Reading and Writing to a File


A third way to implement I/O functionality is to read data from or write data to a file. File I/O is achieved by connecting an I/O stream to a file. File I/O can be done with either byte or character streams. To read or write byte data, you can use the FileInputStream or FileOutputStream classes. To read or write character data, you can use the FileReader or FileWriter classes. Another I/O stream is usually wrapped around the file I/O stream to make it easier to read and write data from the file.

One advantage of using file I/O is it can handle a large number of input parameters. There is no maximum length to an input file. You can also place descriptive comments inside the input file. Another advantage is that you have a permanent record of the input and output. You can reuse an input file or modify a large input file by making only a few changes.

Disadvantages include having to write code to parse the input file. The structure of the input file has to match what the parsing algorithm expects. There are more things that can go wrong with file I/O than the other methods ; an input file may not be found, for example.

The FileDemo class demonstrates how input data can be read from a file and output data can be written to a file. It is especially true about file I/O that there are many ways to accomplish the reading and writing of data. The FileDemo class uses character streams but you could (although it wouldn't be advisable) rewrite the program using byte streams instead.

A FileReader object is created that connects to an input file named "USatm76.inp." A BufferedReader is wrapped around the FileReader to allow the readLine() method to read a line of data at a time. The contents of the "USatm76.inp" file used in this example consist of the following two lines.

 units (SI or English) = SI altitude (m or ft)    = 20000.0 

The first line of the input file contains the system of units to be used. The BufferedReader reads this line as a String , which is then split into substrings using the split() method with the = character as the delimiter . The last substring is the one we want, so we assign it to a String variable named units . The BufferedReader then reads the second line of the input file. Once again the resulting String is split into substrings. The last substring, containing the altitude value we want, is converted into a value of type double and assigned to a variable named altitude . The two inputs are then sent to the USatm76 constructor.

The resulting atmospheric conditions are written to a file using FileWriter and BufferedWriter objects. The FileWriter is connected to a file named "USatm76.out." The BufferedWriter is wrapped around the FileWriter to improve I/O performance. The BufferedWriter object uses its write() method to write a sequence of String objects to the file. The FileDemo class source code is shown here.

 import java.io.*; public class FileDemo {   public static void main(String args[]) {     BufferedReader reader;     BufferedWriter writer;     String line, units;     String strings[];     double altitude;     //  BufferedReader and FileReader objects are     //  used to read input data from a file.     try {       reader = new BufferedReader(                      new FileReader("USatm76.inp"));       //  Read the first line of the input file and       //  split it into substrings.  The last substring       //  is the one we want to keep after any leading       //  and trailing white space is trimmed.       line = reader.readLine();       strings = line.split("=");       units = strings[strings.length-1].trim();       //  Read the second line of the input file.       //  Convert the last substring of the line into a       //  double value containing the altitude.       line = reader.readLine();       strings = line.split("=");       altitude =           Double.parseDouble(strings[strings.length-1]);       //  Create a USatm76 object with the recently       //  acquired input values. Print out the       //  atmospheric data.       USatm76 atm = new USatm76(units, altitude);       //  Use a BufferedWriter and FileWriter object to       //  write the output to a file.       writer = new BufferedWriter(                    new FileWriter("USatm76.out"));       String label[] = atm.getLabels();       //  The write() method will not automatically       //  add a newline character.       writer.write("\ngeometric altitude    = " +                       atm.getAltitude() + label[0]);       writer.write("\ngeopotential altitude = " +             atm.getGeoPotentialAltitude() + label[1]);       writer.write("\ntemperature           = " +                     atm.getTemperature() + label[2]);       writer.write("\npressure              = " +                     atm.getPressure() + label[3]);       writer.write("\nmolar mass            = " +                     atm.getMolarMass() + label[4]);       writer.write("\ndensity               = " +                     atm.getDensity() + label[5]);       //  Close the streams       reader.close();       writer.flush();       writer.close();     } catch (IOException ioe) {       System.out.println("IO Exception occurred");       System.exit(1);     }   } } 

Output (contents of "USatm76.out" file) ”

 geometric altitude    = 20000.0 m geopotential altitude = 19937.27227876952 m temperature           = 216.65 K pressure              = 5529.256361823237 N/m^2 molar mass            = 0.0289645 kg/mole density               = 0.08890932913275061 kg/m^3 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net