Prentice Hall Technical Java Developing Scientific And Engineering Applications Apr 2003 ISBN 0131018159

11 45 0
Prentice Hall Technical Java Developing Scientific And Engineering Applications Apr 2003 ISBN 0131018159

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Character Output Streams The character output stream class hierarchy is shown in Figure 25.4 At the top of the hierarchy is the Writer class that defines methods to write one or more characters to the output stream The BufferedWriter class provides a buffer for improved I/O performance The PrintWriter class can be wrapped around either a character or byte output stream and gives the underlying stream access to the print() and println() methods The OutputStreamWriter class allows you to wrap a character output stream around a byte output stream The FileWriter class connects an output stream to a file allowing you to write data to the file Figure 25.4 Character Output Streams Writer Class The Writer class is the abstract superclass for all character output stream classes It defines methods that are available to all character output streams, including methods to close an output stream, write the contents of a buffer to the stream, or write character or String data to the stream [View full width] public abstract void close() throws IOException public abstract void flush() throws IOException public void write(int c) throws IOException public void write(char[] cbuf) throws IOException public void write(char[] cbuf, int offset, int length) throws IOException public void write(String str) throws IOException public void write(String str, int offset, int length) throws IOException The close() method closes the output stream and releases any resources allocated to it The flush() method causes any data stored in a memory buffer to be written to the stream The write() method is used to write a single character, the contents of a character array, or a String to the output stream You can also write a subset of a character array or String to the output stream BufferedWriter Class The BufferedWriter class provides an intermediary buffer for writing data resulting in more efficient I/O performance Instead of writing characters or Strings immediately to a file, for instance, the character data is first written to the buffer When the buffer reaches its capacity, its contents are written to the file The BufferedWriter class defines two public constructors public BufferedWriter(Writer stream) public BufferedWriter(Writer stream, int bufferSize) A BufferedWriter object is always wrapped around another character output stream The second constructor version allows you to specify the size of the buffer The BufferedWriter class overrides some of the Writer class methods but defines no new methods to write character data To see an example of using a BufferedWriter, see the "Reading and Writing to a File" section later in this chapter FileWriter Class The FileWriter class allows you to connect a character output stream to a file FileWriter objects can be used on their own, but they are often used in conjunction with a BufferedWriter or PrintWriter object to take advantage of the extra functionality provided by those classes The File Writer class does not define any new methods, nor does it override any methods inherited from the OutputStreamWriter or Writer classes The FileWriter class does define five constructors public FileWriter(File file) throws IOException public FileWriter(File file, boolean append) throws IOException public FileWriter(FileDescriptor desc) public FileWriter(String name) throws IOException public FileWriter(String name,boolean append) throws IOException The file can be specified either by a File object, a FileDescriptor object, or by providing the name and, if necessary, path of the file If append is true, data is written starting at the end of the file The default is false meaning that data is written from the beginning of the file OutputStreamWriter Class The OutputStreamWriter class provides a way to wrap a character output stream around a byte output stream Character data is converted to bytes and stored in an intermediate buffer before being written to the underlying stream The OutputStreamWriter class overrides some of the Writer class methods but defines no new methods to write data The class defines four public constructors [View full width] public OutputStreamWriter(OutputStream stream) public OutputStreamWriter(OutputStream stream, Charset cs) public OutputStreamWriter(OutputStream stream, CharsetDecoder dec) public OutputStreamWriter(OutputStream stream, String charsetName) throws UnsupportedEncodingException The first constructor version uses the default character set mapping scheme The other three versions allow you to specify a character mapping to be used PrintWriter Class The PrintWriter class provides an underlying output stream access to the print() and println() methods These methods never throw an IOException and do not need to be enclosed in a try block The Print Writer class is unique in that it can be wrapped around either a character or byte output stream The four PrintWriter class constructors are as follows public PrintWriter(OutputStream stream) public PrintWriter(OutputStream stream, boolean autoFlush) public PrintWriter(Writer stream) public PrintWriter(Writer stream, boolean autoFlush) If autoFlush is true, any call to the println() method will flush the output buffer In addition to overriding some of the Writer class methods, the PrintWriter class defines the following methods public void print(boolean b) public void print(char c) public void print(char[] chars) public void print(double d) public void print(float f) public void print(int i) public void print(long l) public void print(Object obj) public void print(String str) The print() method prints a String or a String representation of a primitive type value or Object to the output stream without appending a newline character to the end of the String public void println() public void println(boolean b) public void println(char c) public void println(char[] chars) public void println(double d) public void println(float f) public void println(int i) public void println(long l) public void println(Object obj) public void println(String str) The println() method prints a String or a String representation of a primitive type value or Object to the output stream A newline character is appended to the end of the String The no-argument version simply writes a newline to the output stream Other Writer Subclasses The Writer class has some other subclasses that you probably won't use much in your scientific and engineering programming work These include the CharArrayWriter, FilterWriter, PipedWriter, and StringWriter classes We won't discuss these classes in this chapter If you want more details, consult the Sun Java doc pages 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 ... The Writer class has some other subclasses that you probably won't use much in your scientific and engineering programming work These include the CharArrayWriter, FilterWriter, PipedWriter, and StringWriter classes We won't discuss these classes in this chapter... The PrintWriter class provides an underlying output stream access to the print() and println() methods These methods never throw an IOException and do not need to be enclosed in a try block The Print Writer class is unique in that it can be... We won't discuss these classes in this chapter If you want more details, consult the Sun Java doc pages Reading and Writing to a File A third way to implement I/O functionality is to read data from

Ngày đăng: 26/03/2019, 17:13

Từ khóa liên quan

Mục lục

  • Figure 25.4

  • Reading and Writing to a File

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan