Вы находитесь на странице: 1из 249

Chapter 19 Binary Input & Output Java I ITP 120

Class #15 Input and Output


Chapter Objectives

To understand how I/O is handled in Java To distinguish between text I/O and binary I/O To read and write bytes using FileInputStream and FileOutputStream

To read and write primitive values and strings using the DataInputStream and DataOutputStream classes
To store and restore objects using ObjectOutputStream and ObjectInputStream, and to understand how objects are serialized and what kind of objects can be serialized

To use the Serializable interface to enable objects to be serializable (optional)


To know how to serialize arrays (optional) To use RandomAccessFile for both read and write (Optional).

Patrick Healy

ITP 120 Java Programming I

Class #15 Input and Output

Overview

The java.io.* package provides a library of classes to read and write various types of data. In Java, all data I/O is handled in the form of streams Data streams can be byte streams or character streams The java.io package has classes that process byte streams of all types NOTE: In Java, a character is 2 BYTES ! Also NOTE: a Unicode character is 2 bytes ! The Reader and Writer classes process character streams. Streams can be layered, so that one type of streams can be converted to another type of streams by chaining. Chaining a character stream reader to a byte stream reader to read bytes on one end and produce characters at the other end .

Patrick Healy

ITP 120 Java Programming I

Class #15 Input and Output

Overview --- Streams

A stream is an abstraction of a continuous one-way flow of data.


Input Stream

Program

File

Output Stream
Patrick Healy
ITP 120 Java Programming I
4

Class #15 Input and Output

2 Types of Stream Classes: Bytes & Characters

The stream classes can be categorized into two types: byte streams and character streams.

The InputStream/OutputStream class is the root of all BYTE stream classes


The Reader/Writer class is the root of all CHARACTER stream classes. The subclasses of InputStream/OutputStream are analogous to the subclasses of Reader/Writer.

Patrick Healy

ITP 120 Java Programming I

Class #15 Input and Output

Byte Stream Classes (note: the word stream )


ByteArrayInputStream DataInputStream FileInputStream BufferedInputStream FilterInputStream LineNumberInputStream InputStream SequenceInputStream PushBackInputStream PipedInputStream ObjectInputStream Object StringBufferInputStream ObjectInput InputData

ByteArrayOutputStream FileOutputStream OutputStream FilterOutputStream PipeOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream ObjectOutput OutputData

Patrick Healy

RandomAccessFile

ITP 120 Java Programming I

Character Stream Classes (Character = 2 bytes)


CharArrayReader InputStreamReader FilterReader Reader StringReader PipedReader BufferedReader Object BufferedWriter CharArrayWriter OutputStreamWriter Writer FilterWriter PipedWriter PrintWriter StringWriter FileWriter LineNumberReader FileReader PushBackReader

Class #15 Input and Output

StreamTokenizer

Patrick Healy

ITP 120 Java Programming I

How is I/O Handled in Java?


A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes.
Scanner input = new Scanner(new File("temp.txt")); System.out.println(input.nextLine());
Program Input object created from an input class Output object created from an output class Input stream 010111001 File

110011011 Output stream

File

Formatter output = new Formatter("temp.txt"); output.format("%s", "Java 101"); output.close();

Text Files vs. Binary Files

Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files. Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a byte-type value C7 in a binary file, because decimal 199 equals to hex C7.

Binary I/O
Text I/O requires encoding and decoding. The JVM converts a Unicode to a file specific encoding when writing a character and coverts a file specific encoding to a Unicode when reading a character. Binary I/O does not require conversions. When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
Text I/O program (a) The Unicode of the character e.g. "199" , Encoding/ Decoding
The encoding of the character is stored in the file 00110001 00111001 00111001 0x31 0x39 0x39

Binary I/O program (b) A byte is read/written e.g. 199 ,


The same byte in the file 00110111 0xC7

Binary I/O Classes


FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream

InputStream
java.io.InputStream +read(): int

The value returned is a byte as an int type. Reads the next byte of data from the input stream. The value byte is returned as
an int value in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value 1 is returned. Reads up to b.length bytes into array b from the input stream and returns the actual number of bytes read. Returns -1 at the end of the stream. Reads bytes from the input stream and stores into b[off], b[off+1], , b[off+len-1]. The actual number of bytes read is returned. Returns -1 at the end of the stream. Returns the number of bytes that can be read from the input stream. Closes this input stream and releases any system resources associated with the stream. Skips over and discards n bytes of data from this input stream. The actual number of bytes skipped is returned.

+read(b: byte[]): int +read(b: byte[], off: int, len: int): int +available(): int +close(): void +skip(n: long): long

+markSupported(): boolean Tests if this input stream supports the mark and reset methods. +mark(readlimit: int): void Marks the current position in this input stream. +reset(): void Repositions this stream to the position at the time the mark method was last called on this input stream.

OutputStream
The value is a byte as an int type.
java.io.OutputStream +write(int b): void +write(b: byte[]): void Writes the specified byte to this output stream. The parameter b is an int value. (byte)b is written to the output stream. Writes all the bytes in array b to the output stream.

+write(b: byte[], off: int, Writes b[off], b[off+1], , b[off+len-1] into the output stream. len: int): void +close(): void +flush(): void Closes this input stream and releases any system resources associated with the stream. Flushes this output stream and forces any buffered output bytes to be written out.

FileInputStream/FileOutputStream
FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream

FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStrea

FileInputStream
To construct a FileInputStream, use the following constructors: public FileInputStream(String filename) public FileInputStream(File file) A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file.

FileOutputStream
To construct a FileOutputStream, use the following constructors:
public FileOutputStream(String filename) public FileOutputStream(File file) public FileOutputStream(String filename, boolean append) public FileOutputStream(File file, boolean append)

TestFileStream

Run

If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter.

FilterInputStream/FilterOutputStream
FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream

Filter streams are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can only be used for reading bytes. If you want to read integers, doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters. FilterInputStream and FilterOutputStream are the base classes for filtering data. When you need to process primitive numeric types, use DatInputStream and DataOutputStream to filter bytes.

DataInputStream/DataOutputStream
DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings.
FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream

DataOutputStream converts primitive type values or strings into bytes and output the bytes to the stream.

DataInputStream
DataInputStream extends FilterInputStream and implements the DataInput interface.
InputStream java.io.DataInput +readBoolean(): boolean Reads a Boolean from the input stream. +readByte(): byte Reads a byte from the input stream. +readChar(): char +readFloat(): float +readDouble(): float DataInputStream +DataInputStream( in: InputStream) +readInt(): int +readLong(): long +readShort(): short +readLine(): String +readUTF(): String Reads a character from the input stream. Reads a float from the input stream. Reads a double from the input stream. Reads an int from the input stream. Reads a long from the input stream. Reads a short from the input stream. Reads a line of characters from input. Reads a string in UTF format.

FilterInputStream

DataOutputStream
DataOutputStream extends FilterOutputStream and implements the DataOutput interface.
OutputStream java.io.DataOutput +writeBoolean(b: Boolean): void Writes a Boolean to the output stream. +writeByte(v: int): void Writes to the output stream the eight low-order bits of the argument v. +writeBytes(s: String): void Writes the lower byte of the characters in a string to the output stream. +writeChar(c: char): void Writes a character (composed of two bytes) to the output stream. +writeChars(s: String): void Writes every character in the string s, to the output stream, in order, two bytes per character. +writeFloat(v: float): void Writes a float value to the output stream. +writeDouble(v: float): void +writeInt(v: int): void +writeLong(v: long): void +writeShort(v: short): void +writeUTF(s: String): void Writes a double value to the output stream. Writes an int value to the output stream. Writes a long value to the output stream. Writes a short value to the output stream. Writes two bytes of length information to the output stream, followed by the UTF representation of every character in the string s.

FilterOutputStream

DataOutputStream +DataOutputStream( out: OutputStream)

Characters and Strings in Binary I/O


A Unicode consists of two bytes. The writeChar(char c) method writes the Unicode of character c to the output. The writeChars(String s) method writes the Unicode for each character in the string s to the output.
Why UTF-8? What is UTF-8?

UTF-8 is a coding scheme that allows systems to operate with both ASCII and Unicode efficiently. Most operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character. The UTF8 is an alternative scheme that stores a character using 1, 2, or 3 bytes. ASCII values (less than 0x7F) are coded in one byte. Unicode values less than 0x7FF are coded in two bytes. Other Unicode values are coded in three bytes.

Using DataInputStream/DataOutputStream
Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors:
public DataInputStream(InputStream instream) public DataOutputStream(OutputStream outstream)

The statements given below create data streams. The first statement creates an input stream for file in.dat; the second statement creates an output stream for file out.dat.
DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); TestDataStream DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat"));

Run

Order and Format


CAUTION: You have to read the data in the same order and same format in which they are stored. For example, since names are written in UTF-8 using writeUTF, you must read names using readUTF.

Checking End of File


TIP: If you keep reading data at the end of a stream, an EOFException would occur. So how do you check the end of a file? You can use input.available() to check it. input.available() == 0 indicates that it is the end of a file.

BufferedInputStream/ BufferedOutputStream
FileInputStream InputStream FilterInputStream

Using buffers to speed up I/O

DataInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream

BufferedInputStream/BufferedOutputStream does not contain new methods. All the methods BufferedInputStream/BufferedOutputStream are inherited from the InputStream/OutputStream classes.

Constructing BufferedInputStream/BufferedOutputStream
// Create a BufferedInputStream public BufferedInputStream(InputStream in) public BufferedInputStream(InputStream in, int bufferSize)

// Create a BufferedOutputStream public BufferedOutputStream(OutputStream out) public BufferedOutputStream(OutputStreamr out, int bufferSize)

Case Studies: Copy File


This case study develops a program that copies files. The user needs to provide a source file and a target file as command-line arguments using the following command:

java Copy source target

The program copies a source file to a target file and displays the number of bytes in the file. If the source does not exist, tell the user the file is not found. If the target file already exists, tell the user the file already exists. Copy Run

Optional

Object I/O
DataInputStream/DataOutputStream enables you to perform I/O for primitive type values and strings. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings.
FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream

Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream

ObjectInputStream
ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants.

java.io.InputStream

ObjectStreamConstants java.io.DataInput java.io.ObjectInput +readObject(): Object Reads an object.

java.io.ObjectInputStream +ObjectInputStream(in: InputStream)

ObjectOutputStream
ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.

java.io.OutputStream

ObjectStreamConstants java.io.DataOutput java.io.ObjectOutput +writeObject(o: Object): void Writes an object.

java.io.ObjectOutputStream +ObjectOutputStream(out: OutputStream)

Using Object Streams


You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors:
// Create an ObjectInputStream public ObjectInputStream(InputStream in)

TestObjectOutputStream // Create an ObjectOutputStream public ObjectOutputStream(OutputStream out) TestObjectInputStream

Run
Run

Random Access Files


All of the streams you have used so far are known as readonly or write-only streams. The external files of these streams are sequential files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and write to at random locations.

RandomAccessFile
DataInput java.io.RandomAccessFile +RandomAccessFile(file: File, mode: String) +RandomAccessFile(name: String, mode: String) +close(): void +getFilePointer(): long +length(): long +read(): int +read(b: byte[]): int +read(b: byte[], off: int, len: int) : int +seek(long pos): void +setLength(newLength: long): void +skipBytes(int n): int +write(b: byte[]): void +write(byte b[], int off, int len) +write(b: byte[], off: int, len: int): void Creates a RandomAccessFile stream with the specified File object and mode. Creates a RandomAccessFile stream with the specified file name string and mode. Closes the stream and releases the resource associated with the stream. Returns the offset, in bytes, from the beginning of the file to where the next read or write occurs. Returns the length of this file. Reads a byte of data from this file and returns 1 an the end of stream. Reads up to b.length bytes of data from this file into an array of bytes. Reads up to len bytes of data from this file into an array of bytes. Sets the offset (in bytes specified in pos) from the beginning of the stream to where the next read or write occurs. Sets a new length of this file. Skips over n bytes of input discarding the skipped bytes. Writes b.length bytes from the specified byte array to this file, starting at the current file pointer. Writes len bytes from the specified byte array starting at offset off to this file. DataInput

File Pointer
A random access file consists of a sequence of bytes. There is a special marker called file pointer that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file file pointer moves forward to the next data. For pointer example, if you read an int value using readInt(), the file byte byte byte byte byte byte byte byte byte byte byte byte (A) Before readInt() JVM reads four bytes from the file pointer and now the file pointer file pointer is four bytes ahead of the previous location.
file byte byte byte byte byte byte byte byte byte byte byte byte (B) Before readInt()

RandomAccessFile Methods
Many methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream. For example, readInt(), readLong(), writeDouble(), readLine(), writeInt(), and writeLong() can be used in data input stream or data output stream as well as in RandomAccessFile streams.

RandomAccessFile Methods, cont.


void

seek(long pos) throws IOException;


Sets the offset from the beginning of the RandomAccessFile stream to where the next read or write occurs.

long

getFilePointer() IOException;
Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs.

RandomAccessFile Methods, cont.


long

length()IOException

Returns the length of the file.


final

void writeChar(int v) throws IOException


Writes a character to the file as a two-byte Unicode, with the high byte written first.

final

void writeChars(String s) throws IOException


Writes a string to the file as a sequence of

RandomAccessFile Constructor
RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); //allows read and write RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); //read only

Optional

Case Studies: Address Book

Now let us use RandomAccessFile to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The Add button stores a new address to the end of the file. The First, Next, Previous, and Last buttons retrieve the first, next, previous, and last addresses from the file, respectively.

Fixed Length String I/O


Random access files are often used to process files of records. For convenience, fixed-length records are used in random access files so that a record can be located easily. A record consists of a fixed number of fields. A field can be a string or a primitive data type. A string in a fixed-length record has a maximum size. file Record is Record 2 Record n If a string 1 smaller than the maximum 1size, the rest ofn Student Student 2 Student e.g., the string is padded with blanks.
Field1 Field 2 Field k name street city state zip

FixedLengthStringIO

End of Presentation Binary Input & Output Chapter 18

Class #15 Input and Output


CopyFile.java

CopyFile.java is a program that copies files. The user needs to provide a source file and a target file as command-line arguments using the following command:

java CopyFile source target

Also: java CompFile source target

The program copies a source file to a target file and displays the number of bytes in the file. If the source does not exist, tell the user the file is not found. If the target file already exists, tell the user the file already exists.

Patrick Healy

ITP 120 Java Programming I

41

Class #15 Input and Output

Object I/O (optional)


DataInputStream/DataOutputStream enables you to perform I/O for primitive type values and strings. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings.

FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream

Patrick Healy

ITP 120 Java Programming I

42

Class #15 Input and Output

ObjectInputStream (optional)
ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants.

java.io.InputStream

ObjectStreamConstants java.io.DataInput java.io.ObjectInput +readObject(): Object Reads an object.

java.io.ObjectInputStream +ObjectInputStream(in: InputStream)

Patrick Healy

ITP 120 Java Programming I

43

Class #15 Input and Output

ObjectOutputStream (optional)
ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.

java.io.OutputStream

ObjectStreamConstants java.io.DataOutput java.io.ObjectOutput +writeObject(o: Object): void Writes an object.

java.io.ObjectOutputStream +ObjectOutputStream(out: OutputStream)

Patrick Healy

ITP 120 Java Programming I

44

Class #15 Input and Output

Using Object Streams (optional)


You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors:

// Create an ObjectInputStream public ObjectInputStream(InputStream in)


// Create an ObjectOutputStream public ObjectOutputStream(OutputStream out) Demo: TestObjectOutputStream.java TestObjectInputStream.java

Patrick Healy

ITP 120 Java Programming I

45

Class #15 Input and Output

The Serializable Interface


Not all objects can be written to an output stream. Objects that CAN be written to an object stream is said to be serializable. A serializable object is an instance of the java.io.Serializable interface. So the class of a serializable object must implement the Serializable interface. The Serializable interface is a marker interface. It has no methods, so you don't need to add additional code in your class that implements Serializable. Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays.

Patrick Healy

ITP 120 Java Programming I

46

Class #15 Input and Output

The transient Keyword


If an object is an instance of Serializable, but it contains non-serializable instance data fields, can the object be serialized? The answer is NO ! To enable the object to be serialized, you can use the transient keyword to mark these data fields to tell the JVM to ignore these fields when writing the object to an object stream.

Patrick Healy

ITP 120 Java Programming I

47

Class #15 Input and Output Consider the following class:

The transient Keyword, cont.

public class ITP120 implements java.io.Serializable { private int v1; private static double v2; private transient A v3 = new A(); } class A { } // A is not serializable

When an object of the ITP120 class is serialized, only variable v1 is serialized. Variable v2 is not serialized because it is a static variable, and variable v3 is not serialized because it is marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.

Patrick Healy

ITP 120 Java Programming I

48

Class #15 Input and Output

Serializing Arrays (optional)


An array is serializable if all its elements are serializable. So an entire array can be saved using writeObject into a file and later restored using readObject. Listing 18.6 stores an array of five int values, an array of three strings, and an array of two JButton objects, and reads them back to display on the console. Demo Program: TestObjectStreamForArray.java

Patrick Healy

ITP 120 Java Programming I

49

Class #15 Input and Output

Random Access Files


All of the streams you have used so far are known as read-only or write-only streams. The external files of these streams are sequential files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and write to at random locations.

Patrick Healy

ITP 120 Java Programming I

50

Class #15 Input and Output


DataInput java.io.RandomAccessFile +RandomAccessFile(file: File, mode: String) +RandomAccessFile(name: String, mode: String) +close(): void +getFilePointer(): long +length(): long +read(): int +read(b: byte[]): int +read(b: byte[], off: int, len: int) : int +seek(long pos): void +setLength(newLength: long): void +skipBytes(int n): int +write(b: byte[]): void +write(byte b[], int off, int len) +write(b: byte[], off: int, len: int): void DataInput

RandomAccessFile

Creates a RandomAccessFile stream with the specified File object and mode. Creates a RandomAccessFile stream with the specified file name string and mode. Closes the stream and releases the resource associated with the stream. Returns the offset, in bytes, from the beginning of the file to where the next read or write occurs. Returns the length of this file. Reads a byte of data from this file and returns 1 an the end of stream. Reads up to b.length bytes of data from this file into an array of bytes. Reads up to len bytes of data from this file into an array of bytes. Sets the offset (in bytes specified in pos) from the beginning of the stream to where the next read or write occurs. Sets a new length of this file. Skips over n bytes of input discarding the skipped bytes. Writes b.length bytes from the specified byte array to this file, starting at the current file pointer. Writes len bytes from the specified byte array starting at offset off to this file.

Patrick Healy

ITP 120 Java Programming I

51

Class #15 Input and Output

File Pointers

A random access file consists of a sequence of bytes. There is a special marker called file pointer that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data. For example, if you read an int value using readInt(), the JVM reads four bytes from the file pointer and now the file pointer is four bytes ahead of the previous location.

Patrick Healy

ITP 120 Java Programming I

52

Class #15 Input and Output

File Pointers (moving the pointer 4 bytes ahead)


file pointer

file

byte byte

byte byte byte byte byte file pointer

byte byte byte byte byte

(A) Before readInt()

file

byte byte

byte byte byte byte byte

byte byte byte byte byte

(B) Before readInt()

Patrick Healy

ITP 120 Java Programming I

53

Class #15 Input and Output


RandomAccessFile

Methods

Many methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream. For example, readInt(), readLong(), writeDouble(), readLine(), writeInt(), and writeLong() can be used in data input stream or data output stream as well as in RandomAccessFile streams.

Patrick Healy

ITP 120 Java Programming I

54

Class #15 Input and Output


RandomAccessFile Methods, cont.

void seek(long pos) throws IOException;


Sets the offset from the beginning of the RandomAccessFile stream to where the next read or write occurs.

long getFilePointer() IOException;


Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs.

Patrick Healy

ITP 120 Java Programming I

55

Class #15 Input and Output


RandomAccessFile Methods, cont.

long length()IOException
Returns the length of the file.

final void writeChar(int v) throws IOException


Writes a character to the file as a two-byte Unicode, with the high byte written first.

final void writeChars(String s) throws IOException


Writes a string to the file as a sequence of characters.

Patrick Healy

ITP 120 Java Programming I

56

Class #15 Input and Output


RandomAccessFile Constructors RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); //allows read and write to the file RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); //read only Demo program: TestRandomAccessFile.java (uses FixedLengthStringIO.java)

Patrick Healy

ITP 120 Java Programming I

57

Case Study: Address Book


Now let us use RandomAccessFile to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The Add button stores a new address to the end of the file. The First, Next, Previous, and Last buttons retrieve the first, next, previous, and last addresses from the file, respectively. Run: AddressBook.java which uses FixedLengthStringIO.java

Chapter 18 Demo Programs


ReadBytes.java (skip) WriteData.java WriteDemo.java ReadData.java ShowFile.java CopyFile.java CopyFileUsingByteStream.java CompFile.java RWData.java RandomAccessDemo.java PrintWriterDemo.java ReadChars.java or BuffReader.java ReadLines.java (BufferedReader)

59

Chapter 18 Demo Programs


TextFileScannerDemo.java

Uses input file morestuff.txt


Uses input file original.txt and creates output file numbered.txt Uses input file: buffer.txt

HasNextLineDemo.java

BufferReaderDemo.java

60

Chapter 18 Demo Programs


TestDataStreams.java TestFileClass.java TestPrintWriters.java ViewFile.java (GUI text file viewer program) needs MyFrameWithExitHanding.java class file ParsingTextFile.java (needs grades.dat file) (creates gradesout.dat) TestRandomAccessFile.java AddressBook.java (creates file address.dat)

needs FixedLengthStringIO.class file


61

Chapter 18 Demo Programs


TestDataStream.java TestFileReader.java (needs temp.txt) TestFileStream.java TestFileWriter.java (needs testdata.txt) TestObjectStreamForArray.java ( creates array.dat) TestObjectOutputStream.java (creates object.dat) TestObjectInputStream.java (reads object.dat)

62

Class #15 Input and Output

Chapter 18 Input / Output

Optional: More on Java File I/O Chapter 18 Java I ITP 120

Patrick Healy

ITP 120 Java Programming I

63

Class #15 Input and Output

Chapter 18: More on Input and Output Stream Classes (byte & character streams)
Predefined

Streams (System.in, System.out, System.err)

Processing External Files Data

Streams Print Streams Buffered Streams Text Input and Output on the Console Random Access Files

Patrick Healy

ITP 120 Java Programming I

64

Chapter 18 Input /Output Objectives


Class #15 Input and Output

Understand input & output streams and learn how to create them.
Discover the uses of byte and character streams. To know how to read from / write to external files using file streams. To become familiar with the File class. To use print streams to output data of primitive types in text format. To know how to read and write text data files. Use text input and output on the console. Use RandomAccessFile for reading & writing random access files.

Patrick Healy

ITP 120 Java Programming I

65

Overview

Class #15 Input and Output

The java.io.* package provides a library of classes to read and write various types of data. In Java, all data I/O is handled in the form of streams Data streams can be byte streams or character streams The java.io package has classes that process byte streams of all types NOTE: In Java, a character is 2 BYTES ! NOTE: Unicode character is 2 bytes ! The Reader and Writer classes process character streams. Streams can be layered, so that one type of streams can be converted to another type of streams by chaining. Chaining a character stream reader to a byte stream reader to read bytes on one end and produce characters at the other end .

Patrick Healy

ITP 120 Java Programming I

66

Overview Streams

Class #15 Input and Output

In Java, all Input/Output is handled by streams


A stream is an abstraction of the continuous one-way flow of data Java streams can be applied to any source of data, so it is easy to get input from the keyboard and send output to a monitor, and the same applies to file input & output. All streams EXCEPT random-access file streams flow only in one direction.

See the diagram on the next slide

Patrick Healy

ITP 120 Java Programming I

67

Class #15 Input and Output

Overview --- Streams

A stream is an abstraction of a continuous one-way flow of data.


Input Stream

Program

File

Output Stream
Patrick Healy
ITP 120 Java Programming I
68

Overview and Background

Class #15 Input and Output

The original version of Java defined only the byte stream, but character streams were quickly added.
Byte streams can be used when reading or writing binary data. Character streams are designed for handling character I/O. Character streams use UNICODE. In Java, a character is 2 bytes Unicode is for the internationalization of Java in different languages. The Java I/O system is quite LARGE because of the TWO separate class hierarchies of bytes and streams.

Patrick Healy

ITP 120 Java Programming I

69

How is I/O Handled in Java?


A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes.
Scanner input = new Scanner(new File("temp.txt")); System.out.println(input.nextLine());
Program Input object created from an input class Output object created from an output class Input stream 010111001 File

110011011 Output stream

File

Formatter output = new Formatter("temp.txt"); output.format("%s", "Java ITP 120"); output.close();

Text Files vs. Binary Files

Class #15 Input and Output

Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files.
Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a byte-type value C7 in a binary file, because decimal 199 equals to hex C7 ( 12 x 16 + 7 = 192 + 7 = 199 decimal )
Patrick Healy
ITP 120 Java Programming I
71

Binary I/O
Text I/O requires encoding and decoding. The JVM converts a Unicode character to file-specific encoding when writing a character, and coverts a file-specific encoding to a Unicode character when reading a character. Binary I/O does not require conversions. When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.
Text I/O program (a) The Unicode of the character e.g. "199" , Encoding/ Decoding
The encoding of the character is stored in the file 00110001 00111001 00111001 0x31 0x39 0x39

Binary I/O program (b) A byte is read/written e.g. 199 ,


The same byte in the file 00110111 0xC7

Class #15 Input and Output

2 Types of Stream Classes: Bytes & Characters

The stream classes can be categorized into two types: byte streams and character streams.

The InputStream/OutputStream class is the root of all byte stream classes


The Reader/Writer class is the root of all character stream classes. The subclasses of InputStream/OutputStream are analogous to the subclasses of Reader/Writer.

Patrick Healy

ITP 120 Java Programming I

73

Class #15 Input and Output

Byte Stream Classes (note: stream )


ByteArrayInputStream DataInputStream FileInputStream BufferedInputStream FilterInputStream LineNumberInputStream InputStream SequenceInputStream PushBackInputStream PipedInputStream ObjectInputStream Object StringBufferInputStream ObjectInput InputData

ByteArrayOutputStream FileOutputStream OutputStream FilterOutputStream PipeOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream ObjectOutput OutputData

Patrick Healy

RandomAccessFile

ITP 120 Java Programming I

74

Character Stream Classes (Character = 2 bytes)


CharArrayReader InputStreamReader FilterReader Reader StringReader PipedReader BufferedReader Object BufferedWriter CharArrayWriter OutputStreamWriter Writer FilterWriter PipedWriter PrintWriter StringWriter FileWriter LineNumberReader FileReader PushBackReader

Class #15 Input and Output

StreamTokenizer

Patrick Healy

ITP 120 Java Programming I

75

Predefined Streams in Java

Class #15 Input and Output

All Java programs automatically import the java.lang package.


The java.lang package defines a class called System which encapsulates several aspects of the runtime environment. The System class contains 3 predefined stream variables called: in, out, and err (System.in, System.out, System.err)

These variables are declared as public and static with the System class. This means they can be used by any other part of your program and without a reference to a specific object in the System class.

Patrick Healy

ITP 120 Java Programming I

76

Predefined Streams in Java:

Class #15 Input and Output

System class

System.in refers to the standard input stream which is the keyboard by default. (Keyboard )
System.out refers to the standard output stream which is the console by default. (Monitor) System.err refers to the standard error stream which is also the console by default. (Monitor) These streams may be redirected to any compatible I/O device.

Patrick Healy

ITP 120 Java Programming I

77

Predefined Streams in Java: System class

Class #15 Input and Output

System.in is an object of type InputStream. (byte stream)


System.out is an object of type PrintStream. (byte stream) System.err is an object of type PrintStream. (byte stream) They are all byte streams and are a part of the original Java specification. They are NOT character streams ! (Unicode character = 2 bytes)

Patrick Healy

ITP 120 Java Programming I

78

Reading Keyboard Input

Class #15 Input and Output

// Read an array of bytes from the keyboard. import java.io.*; public class ReadBytes { public static void main(String[ ] args) throws IOException { byte data[ ] = new byte[10]; // Byte array data holds 10 bytes
System.out.println("Enter some characters:"); System.in.read(data); // Use the read method to read some bytes System.out.print("You entered: "); for(int i=0; i < data.length; i++) System.out.print((char) data[i]); // Cast data to a character } // End main method } // End class ReadBytes
Patrick Healy
ITP 120 Java Programming I
79

Reading Keyboard Input

Class #15 Input and Output

Here is a sample run from the previous program:


(prompt from program) (User entered READ BYTES)

Enter some characters: READ BYTES

You entered: READ BYTES (output from program)

Patrick Healy

ITP 120 Java Programming I

80

Writing Output to the Monitor


// Demonstrate System.out.write(). Java program WriteDemo.java public class WriteDemo { public static void main(String[ ] args) { int b; // Program prints an X on the monitor b = 'X'; // The character is an int System.out.write(b); // A byte stream; write low-order 8 bits System.out.write('\n'); // Print a newline character \n } // End of main( ) // print() and println() are easier to use than write() } // End of class WriteDemo

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

81

Stream classes (Bytes & Characters)

Class #15 Input and Output

The java.io package provides two categories of classes: Byte stream readers and writers Character stream readers and writers At the top of the hierarchy for stream classes are the abstract classes InputStream and Output Stream The subclasses branch out and specializes into the different types of streams that they handle. InputData, OutputData, and ObjectInput interfaces are implemented by the classes that handle data, such as, int, double, char, etc., and objects. Only ObjectInput specifies methods for reading objects. DataInputStream - which is a subclass of FilterInputStream, which in turn is a subclass of InputStream implements the InputData interface and can read primitive data, and objects from byte streams.

Patrick Healy

ITP 120 Java Programming I

82

Stream Classes

Class #15 Input and Output

FileInputStream can read raw streams of data from files.


DataOutputStream can write primitive data; this class implements the OutputData interface RandomAccessFile implements both InputData and OutputData interfaces, therefore, it can read and write data to streams. ObjectOutputStream implements the ObjectOutput interface and can write object data to streams.

Patrick Healy

ITP 120 Java Programming I

83

Class #15 Input and Output


InputStream Class (for reading bytes)

The following methods are defined in InputStream and are often useful:

public abstract int read() throws IOException Reads the next byte and returns its value in the range of 0 to 255. At the end of the stream, it returns a - 1.

public int read(byte b[]) throws IOException


Reads bytes into array b,, returns b.length if the number of available bytes is >= b.length. Returns the number of bytes read if the number of available bytes is < than b.length, and returns 1 at the end of the stream.

Patrick Healy

ITP 120 Java Programming I

84

Class #15 Input and Output


InputStream Class (for reading bytes)

The following methods are defined in InputStream and are often useful:

public void close() throws IOException


This method closes the input stream.

public void available() throws IOException


Returns the number of bytes that can be read from the input stream without blocking.

Patrick Healy

ITP 120 Java Programming I

85

Class #15 Input and Output


InputStream Class (for reading bytes)

The following method is defined in InputStream and is often useful: public long skip(long n) throws IOException Skip over and discard n bytes of data from the input stream. The actual number of bytes skipped is returned.

Patrick Healy

ITP 120 Java Programming I

86

Reading & Writing Files Using Byte Streams

Class #15 Input and Output

To create a byte stream linked to a file, use FileInputStream or FileOutputStream


To open a file, create an object of one of these classes, specifying the name of the file as an argument to the constructor.

Once the file is open, you can read from the file or write to the file.
To read form a file, you may use the read( ) method. int read( ) throws IOException

When you are done with a file, you should close it by calling close()
void close( ) throws IOException Closing a file releases the system resources allocated to the file, allowing them to be used by another file.

Patrick Healy

ITP 120 Java Programming I

87

Reading & Writing Files Using Byte Streams


/* Display a text file.
To use this program, specify the name of the file that you want to see. For example, to see a file called TEST.TXT, use the following command line. Command line usage: // java ShowFile TEST.TXT */

Class #15 Input and Output

Program ShowFile.java follows on the next slide ->

Patrick Healy

ITP 120 Java Programming I

88

Reading & Writing Files Using Byte Streams


public class ShowFile { public static void main(String[ ] args) throws IOException { int i; FileInputStream fin; // Declare file pointer try { fin = new FileInputStream(args[0]); } // Open the input file catch(FileNotFoundException exc) { System.out.println(Error: + exc.getMessage( )); System.out.println("File Not Found"); return; } } catch(ArrayIndexOutOfBoundsException exc) { System.out.println(Error: + exc.getMessage( )); System.out.println("Usage is: java ShowFile File.txt "); return; }

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

89

Reading & Writing Files Using Byte Streams


// Read bytes until EOF is encountered
do { i = fin.read( ); // Read an integer if(i != -1) System.out.print((char) i); // Cast the int as a char } while( i != -1); // When i = -1, EOF is encountered fin.close( ); // Close the input file } // End of main method } // End of class ShowFile

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

90

Writing to a File Using Byte Streams


/* Java program to Copy a text file.
To use this program, specify the name of the source file and the destination file. For example, to copy a file called File1.txt to a file called File2.txt , use the following on the command line: Usage: java CopyFile File1.txt File2.txt */

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

91

Writing to a File Using Byte Streams


// CopyFile.java
import java.io.*; public class CopyFile { public static void main(String[ ] args) { int i; FileInputStream fin; // Declare 2 byte stream files (pointers) FileOutputStream fout; // Output file pointer throws IOException

Class #15 Input and Output

Demo byte stream file operations

Patrick Healy

ITP 120 Java Programming I

92

Writing to a File Using Byte Streams


try { // outer try block

Class #15 Input and Output

// try to open input file try { // inner try fin = new FileInputStream(args[0]); } catch(FileNotFoundException exc) { System.out.println(Error: + exc.getMessage( ) );

System.out.println("Input File Not Found");


return; }
Patrick Healy
ITP 120 Java Programming I
93

Writing to a File Using Byte Streams


// open output file
try { fout = new FileOutputStream(args[1]); } catch(FileNotFoundException exc) { System.out.println(Error: + exc.getMessage()); System.out.println("Error Opening Output File"); return; } } // End of outer try block

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

94

Writing to a File Using Byte Streams


catch(ArrayIndexOutOfBoundsException exc) { System.out.println(Error: + exc.getMessage( ) ); System.out.println("Usage: CopyFile File1 File2"); return; } try { // Try to copy file1 to file2 do { i = fin.read( ); // Read a byte if(i != -1) fout.write(i); // Write the byte to the output file } while(i != -1); // Loop while not at EOF (-1) } // End of try block catch(IOException exc) { System.out.println("File Error"); } fin.close( ); // Close the input file fout.close( ); // Close the output file } // End of main( ) method } // End of class CopyFile ITP 120 Java Programming I Patrick Healy

Class #15 Input and Output

95

Reading & Writing Binary Data


Class #15 Input and Output

So far, we have been reading and writing bytes containing ASCII bytes.
You may want to create a file that contains other types of data such as integers, doubles, or shorts , that is: int, double, short, etc. In Java, to read and write binary values of the simple Java data types, you should use: DataInputStream and DataOutputStream (for binary data)

DataOutputStream implements the OutputData interface. The OutputData interface defines methods that write all of Javas simple data types to a file.

Patrick Healy

ITP 120 Java Programming I

96

Reading & Writing Binary Data

Class #15 Input and Output

Note: Binary data is NOT in human-readable text format, obviously.

The constructor for DataOutputStream is: DataOutputStream(OutputStream outputStream) outputStream is the stream to which the binary data is written.

Patrick Healy

ITP 120 Java Programming I

97

Reading & Writing Binary Data

Class #15 Input and Output

The constructor for DataInputStream is:


DataInputStream(InputStream inputStream) inputStream is the stream that is linked to the instance of DataInputStream being created.

DataInputStream implements the DataInput interface which provides the methods for reading all of Javas simple data types. DataInputStream uses an InputStream instance as its foundation, overlaying it with methods that read the various Java data types.

Patrick Healy

ITP 120 Java Programming I

98

Reading & Writing Binary Data Examples


To create an input stream for the file in.dat ( bytes)
DataInputStream infile = new DataInputStream(new FileInputStream(in.dat)); To create an output stream for the file out.dat: DataOutputStream outfile = new DataOutputStream(new FileOutputStream(out.dat));

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

99

Reading & Writing Binary Data

Class #15 Input and Output

Common Input Methods Defined by DataInputStream (a byte stream)


Input Method Purpose Reads a boolean Reads a byte Reads a char Reads a double Reads a float Reads an int Reads a long Reads a short

boolean readBoolean ( ) byte readByte ( ) char readChar ( ) double readDouble( ) float readFloat ( ) int readInt ( ) long readLong ( ) short readShort ( )

Patrick Healy

ITP 120 Java Programming I

100

Reading & Writing Binary Data

Class #15 Input and Output

Common Output Methods Defined by DataOutputStream ( byte stream)


Output Method Purpose writes the boolean specified by val writes the low-order byte val writes the value val as a char writes the double val writes the float val writes the int val writes the long val writes val as a short

void writeBoolean (boolean val) void writeByte (int val) void writeChar(int val) void writeDouble(double val) void writeFloat(float val) void writeInt(int val) void writeLong(long val) void writeShort(int val)

Patrick Healy

ITP 120 Java Programming I

101

Reading & Writing Binary Data

Class #15 Input and Output

Here is a Java program that demonstrates DataOutputStream and DataInputStream. It writes and then reads back various types of data to and from a file.

// Write and then read back binary data.

import java.io.*;
public class RWData { public static void main(String[ ] args) throws IOException

{
DataOutputStream dataOut; // Declare output, input file pointers DataInputStream dataIn;

Patrick Healy

ITP 120 Java Programming I

102

Reading & Writing Binary Data


int i = 120; double d = 1049.56; boolean b = true; try { dataOut = new DataOutputStream(new FileOutputStream(testdata")); } catch(IOException exc) { System.out.println(Error: + exc.getMessage( )); System.out.println("Cannot open file."); return; }

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

103

Reading & Writing Binary Data


try { // Write the binary data System.out.println("Writing " + i); dataOut.writeInt(i);
System.out.println("Writing " + d); dataOut.writeDouble(d); System.out.println("Writing " + b); dataOut.writeBoolean(b); System.out.println("Writing " + 12.2 * 7.4); dataOut.writeDouble(12.2 * 7.4); }
Patrick Healy
ITP 120 Java Programming I
104

Class #15 Input and Output

Reading & Writing Binary Data


catch(IOException exc) { System.out.println("Write error: + exc.getMessage( )"); } dataOut.close( ); System.out.println(); // Print a blank line // Now, read them back. try { dataIn = new DataInputStream(new FileInputStream("testdata")); } catch(IOException exc) { System.out.println("Cannot open file. + exc.getMessage( )"); return; }
Patrick Healy
ITP 120 Java Programming I
105

Class #15 Input and Output

Reading & Writing Binary Data


try {
i = dataIn.readInt(); System.out.println("Reading " + i);

Class #15 Input and Output

// Read the binary data

d = dataIn.readDouble();
System.out.println("Reading " + d); b = dataIn.readBoolean(); System.out.println("Reading " + b); d = dataIn.readDouble(); System.out.println("Reading " + d); }
Patrick Healy
ITP 120 Java Programming I
106

Reading & Writing Binary Data


catch(IOException exc) {
System.out.println("Read error. + exc.getMessage( ) ); } dataIn.close(); } // End of main ( ) } // End of class RWData The output from the previous program follows: Writing 120 Writing 1023.56 Writing true Writing 90.28 Reading 120 Reading 1049.56 Reading true Reading 90.28

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

107

Class #15 Input and Output Reader class methods for reading characters The Reader class is similar to the InputStream class. The methods in Reader are subject to character interpretation.

Remember: A character is 2 bytes ! public abstract int read() throws IOException

public int read(char b[]) throws

IOException

public void close() throws IOException public void skip() throws IOException

Patrick Healy

ITP 120 Java Programming I

108

OutputStream ( bytes) & Writer (for characters)

Class #15 Input and Output

Like InputStream (for reading bytes) and Reader (for reading characters), OutputStream and Writer are the counterparts. They are the base classes for for all output streams of bytes and characters, respectively.

The next slide shows methods which are in both OutputStream and Writer. See next slide ->

Patrick Healy

ITP 120 Java Programming I

109

Class #15 Input and Output OutputStream

(Writing bytes)

public abstract void write(int b) throws IOException Write a byte b (for OutputStream) or a charcter (for Writer) public void write(byte[] b) throws IOException This method writes all bytes in the array b to the output stream (for OutputStream) or characters in the array of characters (for Writer)

public void close() throws IOException This method closes the output stream. public void flush() throws IOException Flush the output stream and send any buffered data in the stream to its destination.

Patrick Healy

ITP 120 Java Programming I

110

Class #15 Input and Output


Writer (Writing characters) (Same as OutputStream)

public abstract void write(int b) throws IOException Write a byte b (for OutputStream) or a character (for Writer) public void write(byte[] b) throws IOException This method writes all bytes in the array b to the output stream (for OutputStream) or characters in the array of characters (for Writer)

public void close() throws IOException This method closes the output stream. public void flush() throws IOException Flush the output stream and send any buffered data in the stream to its destination.

Patrick Healy

ITP 120 Java Programming I

111

Console Input using Character Streams


For Java code that will be internationalized, inputting data from the console using Javas character-based streams is a better, more convenient way to read characters from the keyboard than using byte streams.
Since System.in is a byte-stream, you need to wrap System.in inside of some type of Reader. The best class for reading console input is BufferedReader which supports a buffered input stream. (BufferedReader inherits from Reader) But, you cannot construct a BufferedReader directly from System.in

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

112

Console Input using Character Streams


You must first convert the input from System.in from a byte stream into a character stream. To do this, you must use InputStreamReader.
InputStreamReader converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader ( InputStream inputStream ) Since System.in refers to an object of type InputStream, it can be used for inputStream such as in: InputStreamReader(System.in)

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

113

Console Input using Character Streams


Next, using the object produced by InputStreamReader, construct a BufferedReader using the following constructor:
BufferedReader(Reader inputReader) Here, inputReader is the stream that is linked to the instance of BufferedReader being created.

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

114

Console Input using Character Streams


Putting it all together, the following line of code creates a BufferReader that is connected to the keyboard.
BufferedReader br =

Class #15 Input and Output

new BufferedReader( new InputStreamReader(System.in));


After the above statement executes, br will be a character-based

stream that is linked to the console thru System.in (which reads bytes)

Patrick Healy

ITP 120 Java Programming I

115

Console Input using Character Streams

Class #15 Input and Output

Reading Characters
Characters can be read from System.in using the read( ) method defined by BufferedReader.

BufferedReader defines the following versions of read( )


int read( ) throws IOException int read(char data[ ] ) throws IOException int read(char data[ ], int start, int max) throws IOException

Patrick Healy

ITP 120 Java Programming I

116

Console Input using Character Streams

Class #15 Input and Output

int read( ) throws IOException reads a single Unicode character and returns a -1 when the end of the stream is reached. int read(char data[ ]) throws IOException reads characters from the input stream until: (1) the array is full, (2) EOF is reached, or (3) an error occurs. int read(char data[ ], int start, int max) throws IOException reads input into array data beginning at the location specified by start, storing up to max characters. It returns the number of characters read or -1 when the end of the stream is reached. Pressing the [Enter] key generates an end-of-stream condition.

Patrick Healy

ITP 120 Java Programming I

117

Console Input using Character Streams

Class #15 Input and Output

The following program demonstrates the read( ) method by reading characters from the console until the user types a period.

// Use a BufferedReader to read characters from the console. import java.io.*; public class ReadChars { public static void main(String[ ] args) throws IOException {

Patrick Healy

ITP 120 Java Programming I

118

Console Input using Character Streams


BufferedReader br = new
BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter some characters; period to quit."); // read characters do { c = (char) br.read(); // Cast the character to a byte System.out.println(c); // Print the character } while(c != '.'); // Loop as long as the input char is not a period } // End of main method } // End of ReadChars class

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

119

Console Input using Character Streams


Output from the previous program could be: Enter some characters; period to quit. I T P

Class #15 Input and Output

J A V A .

<- note the period character which stopped the input stream

Patrick Healy

ITP 120 Java Programming I

120

Console Input using Character Streams

Class #15 Input and Output

Reading Character Strings from the Keyboard


To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. The general form is:

String readLine( ) throws IOException It returns a string object that contains the characters read. It returns null if an attempt is made to read beyond the end of the stream.

Patrick Healy

ITP 120 Java Programming I

121

Console Input using Character Streams

Class #15 Input and Output

The following program demonstrates BufferedReader and the readLine() method. The program reads and displays lines of text until the user enters the word stop
import java.io.*;

// Read a string from console using a BufferedReader. class ReadLines { public static void main(String[ ] args) throws IOException {

// create a BufferedReader using System.in


BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str;

Patrick Healy

ITP 120 Java Programming I

122

Console Input using Character Streams


System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while(!str.equals("stop")); } // End of main method } // End of class ReadLines

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

123

Console Output using Character Streams

Class #15 Input and Output

The preferred method of writing to the console (monitor) when using Java is through a PrintWriter stream.
PrintWriter is one of the character-based classes. Using a character-based class makes it easier to internationalize Java programs. PrintWriter has several constructors, but this is the one to be used in the demonstration program which is on the following slides:

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

Patrick Healy

ITP 120 Java Programming I

124

Console Output using Character Streams


PrintWriter(OutputStream outputStream, boolean flushOnNewline)
Here, outputStream is an object of type OutputStream. flushOnNewLine controls whether Java flushes the output stream every time a println( ) method is called. If flushOnNewLine is true flushing automatically takes place.

Class #15 Input and Output

If flushOnNewLine is false, flushing is not automatic.

Patrick Healy

ITP 120 Java Programming I

125

Console Output using Character Streams


To write to the console (monitor) using a PrintWriter, specify System.out for the output stream and flush the stream after each call to println( ).
For example, the following line of code creates a PrintWriter that is connected to console (monitor) output. PrintWriter pw = new PrintWriter(System.out, true); The Java program on the next slide demonstrates a PrintWriter

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

126

Console Output using Character Streams


// Demonstrate PrintWriter.
import java.io.*; public class PrintWriterDemo { public static void main(String[ ] args) { PrintWriter pw = new PrintWriter(System.out, true); int i = 120; double d = 123.67;

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

127

Console Output using Character Streams


pw.println("Using a PrintWriter."); // PrintWriter Demo pw.println(i); pw.println(d); pw.println(i + " + " + d + " is " + i +d); } // End of main( ) method } // End of class PrintWriterDemo The output from the previous program is: Using a PrintWriter. 120 123.67 120 + 123.67 is 243.67

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

128

File Input & Output using Character Streams


In general, to perform character-based file I/O, you will use the FileReader and FileWriter classes.
Using a FileWriter FileWriter creates a Writer that you can use to write to a file. FileWriter is derived from OutputStreamWriter and Writer classes Commonly used constructors are: FileWriter (String fileName) throws IOException FileWriter (String fileName, boolean append) throws IOException fileName is the full path name of the file. If append is true, then output is appended to the end of the file. Otherwise, the file is overwritten.
ITP 120 Java Programming I
129

Class #15 Input and Output

Patrick Healy

File I / O using Character Streams FileWriter


// A simple keyboard-to-disk utility that demonstrates a FileWriter.
import java.io.*; public class KtoD { public static void main(String[ ] args) throws IOException { String str; FileWriter fw; BufferedReader br = new BufferedReader( new InputStreamReader(System.in));

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

130

File I / O using Character Streams FileWriter


try {
fw = new FileWriter("test.txt"); // Try to open the file } catch(IOException exc) { System.out.println(Error: + exc.getMessage( ) ); System.out.println("Cannot open output file."); return ; }

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

131

File I / O using Character Streams FileWriter


System.out.println("Enter text ('stop' to quit)."); do { System.out.print(": "); str = br.readLine( ); if(str.compareTo("stop") == 0) break; str = str + "\r\n"; // add carriage return & newline fw.write(str); } while(str.compareTo("stop") != 0); fw.close( ); } // End of main ( ) method } // End of class KtoD

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

132

File I / O using Character Streams FileReader


The FileReader class creates a Reader that you can use to read the
contents of a file. FileReader is derived from the InputStreamReader and Reader classes. It has access to the methods in those classes. The most common constructor is: FileReader(String fileName) throws FileNotFoundException where fileName is the full path name of the file. It throws a FileNotFoundException if the file does not exist.

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

133

File I / O using Character Streams FileReader


The following program reads a text file called test.txt and displays the information on the screen.
// A simple disk-to-screen utilitiy that demonstrates a FileReader. import java.io.*; class DtoS { public static void main(String[ ] args) throws Exception { FileReader fr = new FileReader("test.txt"); BufferedReader br = new BufferedReader(fr); String s;

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

134

File I / O using Character Streams FileReader


while((s = br.readLine()) != null)
{ System.out.println(s); } fr.close( ); // Close the file } // End of main( ) method } // End of DtoS class

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

135

Class #15 Input and Output


The File Class: Objectives

To discover file properties, delete and rename files using the File class To understand how I/O is processed in Java To distinguish between text I/O and binary I/O To read and write characters using FileReader and FileWriter To improve the performance of text I/O using BufferedReader and BufferedWriter To write primitive values, strings, and objects as text using PrintWriter and PrintStream To read and write bytes using FileInputStream and FileOutputStream To read and write primitive values and strings using DataInputStream/DataOutputStream To store and restore objects using ObjectOutputStream and ObjectInputStream, and to understand how objects are serialized and what kind of objects can be serialized To use RandomAccessFile for both read and write.

Patrick Healy

ITP 120 Java Programming I

136

Class #15 Input and Output

The File Class

The File class is intended to provide an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion. The filename is a string. The File class is a wrapper class for the file name and its directory path.

Patrick Healy

ITP 120 Java Programming I

137

java.io.File Class #15 Input and Output


Obtaining file properties and manipulating file

+File(pathname: String)

Creates a File object for the specified pathname. The pathname may be a directory or a file.

+File(parent: String, child: String) Creates a File object for the child under the directory parent. child may be a filename or a subdirectory. +File(parent: File, child: String) Creates a File object for the child under the directory parent. parent is a File object. In the preceding constructor, the parent is a string. +exists(): boolean Returns true if the file or the directory represented by the File object exists. +canRead(): boolean +canWrite(): boolean +isDirectory(): boolean +isFile(): boolean +isAbsolute(): boolean +isHidden(): boolean Returns true if the file represented by the File object exists and can be read. Returns true if the file represented by the File object exists and can be written. Returns true if the File object represents a directory. Returns true if the File object represents a file. Returns true if the File object is created using an absolute path name. Returns true if the file represented in the File object is hidden. The exact definition of hidden is system-dependent. On Windows, you can mark a file hidden in the File Properties dialog box. On Unix systems, a file is hidden if its name begins with a period character '.'. Returns the complete absolute file or directory name represented by the File object. Returns the same as getAbsolutePath() except that it removes redundant names, such as "." and "..", from the pathname, resolves symbolic links (on Unix platforms), and converts drive letters to standard uppercase (on Win32 platforms). Returns the last name of the complete directory and file name represented by the File object. For example, new File("c:\\book\\test.dat").getName() returns test.dat. Returns the complete directory and file name represented by the File object. For example, new File("c:\\book\\test.dat").getPath() returns c:\book\test.dat. Returns the complete parent directory of the current directory or the file represented by the File object. For example, new File("c:\\book\\test.dat").getParent() returns c:\book. Returns the time that the file was last modified. Deletes this file. The method returns true if the deletion succeeds.

+getAbsolutePath(): String +getCanonicalPath(): String

+getName(): String

+getPath(): String +getParent(): String

+lastModified(): long +delete(): boolean

Patrick Healy

+renameTo(dest: File): Boolean

ITP 120Renames this file. The method returns true if the operation succeeds. Java Programming I

138

Example Using the File Class

Class #15 Input and Output

TestFileClass.java

Objective: Write a program that demonstrates how to create files in a platform-independent way and use the methods in the File class to obtain their properties. Figure 1 shows a sample run of the program on Windows, and Figure 2 a sample run on Unix (Windows) (Unix)

Patrick Healy

ITP 120 Java Programming I

139

The File Class and Processing External Files

Class #15 Input and Output

The File class provides an abstraction that deals with most of the machine-dependent complexities of files and path names in a machineindependent fashion. You can create a new File object using the following statement:
File myfile = new File (myfile.dat);

You can use the File class to check properties of files, such as whether the file exists, or is readable, or updateable.

Patrick Healy

ITP 120 Java Programming I

140

The File Class and Processing External Files


Class #15 Input and Output

You can use the getName( ) method to get the name of the file.
For example, if (myfile.exists( ) ) System.out.println(File + myfile.getName( ) + already exists);

The following statement creates a file using the full path using the Windows operating system: File myfile = new File(C:\\Java\\myfile.data);

Patrick Healy

ITP 120 Java Programming I

141

The File Class and Processing External Files

Class #15 Input and Output

You can use the getPath( ) method to get the full path of the file and the getParent( ) method to get the directory that contains the file.
For example, if (myfile.exists( ) ) { System.out.println(The full path is + myfile.getPath( ) ); System.out.println(The directory is + myfile.getParent( ) ); }

Patrick Healy

ITP 120 Java Programming I

142

Demo Program: TestFileClass.java


// TestFileClass.java: Demonstrate the File class Chapt 18 I/O ITP120 import java.io.*; import java.util.*;
public class TestFileClass { public static void main(String[] args) { // Create a File object File file = new File(".", "images" + File.separator + "bill_gates.gif"); System.out.println("Does it exist? " + file.exists()); System.out.println("Can it be read? " + file.canRead()); System.out.println("Can it be written? " + file.canRead()); System.out.println("Is it a directory? " + file.isDirectory()); System.out.println("Is it a file? " + file.isFile()); System.out.println("Is it absolute? " + file.isAbsolute()); System.out.println("Is it hidden? " + file.isHidden()); System.out.println("What is its absolute path? " + file.getAbsolutePath());
143

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

Demo Program: TestFileClass.java


try { System.out.println("What is its canonical path? " + file.getCanonicalPath()); } catch (IOException ex) { }
System.out.println("What is its name? " + file.getName()); System.out.println("What is its path? " + file.getPath()); System.out.println("When was it last modified? " + new Date(file.lastModified())); System.out.println("What is the path separator? " + File.pathSeparatorChar); System.out.println("What is the name separator? " + File.separatorChar);

Class #15 Input and Output

}
}
144

Patrick Healy

ITP 120 Java Programming I

Class #15 Input and Output

Processing External Files


Again, you must use file streams to read from or write to a disk file. Once again, you can use FileInputStream or FileOutputStream for byte streams. And you can use FileReader or FileWriter for character streams.

Patrick Healy

ITP 120 Java Programming I

145

File I/O Stream Constructors

Class #15 Input and Output

To create a file stream, use these constructors:


// Byte stream constructors

public FileInputStream (String filenameString) public FileInputStream (File file)

public FileOutputStream (String filenameString) // Byte stream constructor


public FileOutputStream (File file) public FileReader (String filenameString) public FileReader (File file) public FileWriter (String filenameString) // Character stream constructor public FileWriter (File file) // Character stream constructors

Patrick Healy

ITP 120 Java Programming I

146

Class #15 Input and Output

File I/O Stream Constructors


Constructing instances of FileInputStream, FileOutputStream, FileReader, and FileWriter from file names:

FileInputStream infile = new FileInputStream("in.dat"); FileOutputStream outfile = new FileOutputStream("out.dat"); FileReader infile = new FileReader("in.dat"); FileWriter outfile = new FileWriter("out.dat");

Patrick Healy

ITP 120 Java Programming I

147

Demo Program: TestFileReader.java


// TestFileReader.java Chapter 18 I/O ITP 120 import java.io.*; public class TestFileReader { public static void main(String[ ] args) { FileReader input = null; try { // Create an input stream input = new FileReader("temp.txt"); int code; // Repeatedly read a character and display it on the console while ((code = input.read()) != -1) System.out.print((char)code); } // End of try block
Patrick Healy
ITP 120 Java Programming I
148

Class #15 Input and Output

Demo Program: TestFileReader.java


System.out.println("File temp.txt does not exist"); } catch (IOException ex) { ex.printStackTrace(); } finally { try { input.close(); // Close the stream } catch (IOException ex) { ex.printStackTrace(); } } } // End of class TestFileReader

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

149

Demo Program: TestFileWriter.java


// TestFileWriter.java import java.io.*; Chapter 18 File I/O ITP 120

Class #15 Input and Output

public class TestFileWriter { public static void main(String[ ] args) throws IOException { // Create an output stream to the file FileWriter output = new FileWriter("temp.txt", true); // Output a string to the file output.write( NVCC Introduction to Java Programming ITP 120 !!!"); // Close the stream output.close(); } }

Patrick Healy

ITP 120 Java Programming I

150

Processing External Files

Class #15 Input and Output

FileInputStream fis program FileOutputStream fos

args[0] args[1]

Patrick Healy

ITP 120 Java Programming I

151

Processing External Files

Class #15 Input and Output

The previous diagram shows that:


FileInputStream, fis, is used to read data (bytes) from a file FileOutputStream, fos, is used to write data (bytes) to a file Command line: java CopyFileUsingByteStream f1.txt f2.txt

See the Java program CopyFileUsingByteStream on the following slides

Patrick Healy

ITP 120 Java Programming I

152

Processing External Files


// CopyFileUsingByteStream.java
import java.io.*;

Class #15 Input and Output

For Copying files (byte streams)

public class CopyFileUsingByteStream { // Main method: args[0] for sourcefile and args[1] for target file public static void main(String[ ] args) { // Declare input and output file streams FileInputStream fis = null; FileOutputStream fos = null;

Patrick Healy

ITP 120 Java Programming I

153

Processing External Files

Class #15 Input and Output

if (args.length !=2) // args[0] is source file { // args[1] is target file System.out.println(

"Usage: java CopyFileUsingByteStream f1 f2");


System.exit(0); // Stop the program }

Patrick Healy

ITP 120 Java Programming I

154

Processing External Files


try
{ // Create file input stream

Class #15 Input and Output

fis = new FileInputStream(new File(args[0])); // Create file output stream if the file does not exist File outFile = new File(args[1]); if (outFile.exists()) { System.out.println("file " + args[1] + " already exists"); return; }

Patrick Healy

ITP 120 Java Programming I

155

Processing External Files


else

Class #15 Input and Output

fos = new FileOutputStream(args[1]); // FileOutputStream // Display the file size System.out.println("The file " + args[0] + " has "+ fis.available() + " bytes");

Patrick Healy

ITP 120 Java Programming I

156

Processing External Files


int r; while ((r = fis.read()) != -1) fos.write((byte)r); }

Class #15 Input and Output

// Continuously read a byte from fis and write it to fos


// EOF is -1

catch (FileNotFoundException ex) { System.out.println(Error: + ex.getMessage( ) ); System.out.println("File not found: " + args[0]); }

Patrick Healy

ITP 120 Java Programming I

157

Processing External Files


catch (IOException ex)
{

Class #15 Input and Output

System.out.println(Some IO Exception occurred); System.out.println(Error: + ex.getMessage( )); } Continues to next slide

Patrick Healy

ITP 120 Java Programming I

158

Processing External Files

Class #15 Input and Output

finally { try { if (fis != null) fis.close(); // Close the input & output files if (fos != null) fos.close(); } catch (IOException ex) { System.out.println(Error: + ex.getMessage( ) ); } } // End of finally block } // End of main method } // End of class CopyFileUsingByteStream
Patrick Healy
ITP 120 Java Programming I
159

Class #15 Input and Output

Filter Streams

Filter streams are streams that filter bytes or characters for some purpose.
If you want to read integers, doubles, or Strings, you need a filter class to wrap the input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters. Use FilterInputStream and FilterOutputStream when you need to process primitive numeric types.

Patrick Healy

ITP 120 Java Programming I

160

Filter Streams

Class #15 Input and Output

To process strings, use BufferedReader and PushbackReader to filter characters.


Note: FilterInputStream and FilterOutputStream are abstract classes.

Patrick Healy

ITP 120 Java Programming I

161

FilterInputStream subclasses

Class #15 Input and Output

DataInputStream handles binary formats for all primitive data types.


BufferedInputStream gets data from the buffer and then reads them from the stream if necessary. LineNumberInputStream keeps track of how many lines are read. PushBackInputStream allows single-byte look-a-head. Looks at a byte and pushes it back to the stream if the byte read is NOT the desired byte.

Patrick Healy

ITP 120 Java Programming I

162

FilterOutputStream subclasses

Class #15 Input and Output

DataOutputStream outputs the binary formats for all primitive data types which is useful if another program uses the output. BufferedOutputStream outputs to the buffer first and then to the stream if necessary. You may also call the flush( ) method to write the buffer to the stream. PrintStream outputs the Unicode format of all primitive types which is useful if the format is output to the console.

Patrick Healy

ITP 120 Java Programming I

163

Class #15 Input and Output

Data Streams

(bytes)

The data streams (DataInputStream and DataOutputStream) read and write Java primitive types in a machine-independent fashion. This enables you to write a data file for one computer and read it on another computer that has a different operating system or file structure.

Patrick Healy

ITP 120 Java Programming I

164

Class #15 Input and Output


DataInputStream Methods defined in the DataInput Interface

int readByte() throws IOException int readShort() throws IOException int readInt() throws IOException int readLong() throws IOException

float readFloat() throws IOException


double readDouble() throws IOException char readChar() throws IOException

boolean readBoolean() throws IOException


String readUTF() throws IOException
ITP 120 Java Programming I
165

Patrick Healy

Class #15 Input and Output

DataOutputStream Methods defined in the DataOutput interface


void writeByte(byte b) throws IOException void writeShort(short is) throws IOException void writeInt(int i) throws IOException void writeLong(long l) throws IOException void writeFloat(float f) throws IOException void writeDouble(double d) throws IOException void writeChar(char c) throws IOException void writeBoolean(boolean b) throws IOException void writeBytes(String s) throws IOException void writeChars(String s) throws IOException void writeUTF(String s) throws IOException

Patrick Healy

ITP 120 Java Programming I

166

Class #15 Input and Output

DataInputStream & DataOutput Stream Constructors

Data streams are used as wrappers on existing input and output streams to filter data in the original stream.
DataInputStream infile = new DataInputStream(new FileInputStream("in.dat"));

The above creates an input file for in.dat.

DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat"));

The above creates an output file for out.dat.


Patrick Healy
ITP 120 Java Programming I
167

Using Data Streams

Class #15 Input and Output

The next example shows a program that:


1) 2) 3) 4) Creates 10 random integers, Stores them in a data file, Retrieves data from the file, Displays the integers on the console. See next slide

Patrick Healy

ITP 120 Java Programming I

168

Using Data Streams

Class #15 Input and Output

Demo Example

// TestDataStreams.java: Create a file, store it in binary form, and


// display the contents of the file on the console import java.io.*;

public class TestDataStreams


{ // Main method public static void main(String[ ] args) { // Declare data input and output streams DataInputStream dis = null; DataOutputStream dos = null;

Patrick Healy

ITP 120 Java Programming I

169

Using Data Streams


// Construct a temp file

Class #15 Input and Output

Demo Example

File tempFile = new File("mytemp.dat"); // Check if the temp file exists if (tempFile.exists()) { System.out.println("The file mytemp.dat already exists," +" delete it, rerun the program"); System.exit(0); }

Patrick Healy

ITP 120 Java Programming I

170

Using Data Streams


// Write data
try {

Class #15 Input and Output

Demo Example

// Create data output stream for tempFile dos = new DataOutputStream(new FileOutputStream(tempFile)); for (int i=0; i<10; i++) dos.writeInt((int)(Math.random()*1000)); }

Patrick Healy

ITP 120 Java Programming I

171

Using Data Streams


catch (IOException ex)
{

Class #15 Input and Output

Demo Example

System.out.println(ex.getMessage( ) ); }

finally
{ try { if (dos != null) dos.close( ); } catch (IOException ex) { System.out.println(Error: + ex.getMessage( ) ); } // Close the file(s)

Patrick Healy

ITP 120 Java Programming I

172

Using Data Streams


// Read data
try {

Class #15 Input and Output

Demo Example

// Create data input stream dis = new DataInputStream(new FileInputStream(tempFile)); for (int i=0; i<10; i++) System.out.print(" "+dis.readInt ( ) ); // Display the integers }

Patrick Healy

ITP 120 Java Programming I

173

Using Data Streams


{

Class #15 Input and Output

catch (FileNotFoundException ex)


System.out.println("File not found + ex.getMessage( ) );); } catch (IOException ex) { System.out.println(ex.getMessage()); }

Patrick Healy

ITP 120 Java Programming I

174

Using Data Streams


finally
{ try {

Class #15 Input and Output

if (dis != null)
}

dis.close( ); // Close the file(s)

catch (IOException ex) { System.out.println(Error: + ex.getMessage( ) )); } } // End of finally block } // End of main method } // End of class TestDataStreams
Patrick Healy
ITP 120 Java Programming I
175

Using Data Streams

Class #15 Input and Output

Demo Example

The previous Java program TestDataStreams.java creates a DataInputStream object named dis wrapped on FileInputStream and creates a DataOutputStream object dos wrapped on FileOutputStream Conceptually,

Program DataInputStream dis <-- fileInputStream <--mytemp.dat DataOutputStream dos fileOutputStream mytemp.dat The program uses a temporary file, mytemp.dat, to store data. The program creates mytemp.dat if it does not exist and writes 10 random

integers into mytemp.dat. The data in mytemp.dat is in binary format.

Patrick Healy

ITP 120 Java Programming I

176

Character Classes

Class #15 Input and Output

The classes that handle characters have at the top of their hierarchy, Reader and Writer
The subclasses branch out to provide specialized functionality. FileReader provides functionality for reading streams of characters from files. BufferedReader buffers character streams for efficiency FileWriter for writing character streams to files.

PrintWriter for writing character streams.


ITP 120 Java Programming I
177

Patrick Healy

File Class

Class #15 Input and Output


File class provides functionality for working directly with files in the operating system
The File class provides overloaded constructors for creating File objects. A File object can be created by giving the name of the file: File inputFile = new File(in.dat); // Same directory File myInputFile = new File(C:\\myDirectory\\in.dat); A File Object can refer to either a file or directory File theDir = new File(C:\\myDir); //File object theDir refers to a directory Some File class methods: exists() that tests if the named file already exist. mkdir( String st ) for creating directories list() for listing the contents of directories getPath() gets the path of the named file length() returns the file size in bytes

Patrick Healy

ITP 120 Java Programming I

178

File Class

Class #15 Input and Output


Example: DirectoryContents.java listing the contents of a directory using File class import java.io.*; public class DirectoryContents { public static void main(String[ ] args) { File myDir = new File(C:\\"); if(myDir.isDirectory( ) ) { System.out.println("Contents of directory " + myDir ); String[ ] contents = myDir.list(); for( int I = 0; I < contents.length; I++) System.out.println(contents[ I ] ); } // End of if block } // End of main method } // End of class DirectoryContents
ITP 120 Java Programming I
179

Patrick Healy

Using Java I/O

Class #15 Input and Output

Many of the methods including constructors of Java.io classes throw exceptions:


The most commonly thrown is IOException.

Reading data from the keyboard BufferedReader in = new BufferedReader(new InputStreamReader(System.in); An InputStreamReader is like an adapter, it reads byte streams and converts it into character streams BufferedReader wraps the InputStreamReader to provide extra functionality, allowing to buffer the input to support readLine()

Patrick Healy

ITP 120 Java Programming I

180

Using Java I/O

Class #15 Input and Output

Example Reading strings from the keyboard Import java.io.* public class ReadStringFromKeyboard { public static void main(String[ ] args) { // Converts from bytes to characters BufferedReader in = new BufferedReader(new InputStreamReader (System.in)); String yourInput; try { System.out.println("Please enter any string and hit the return key when done:"); yourInput = in.readLine( ); System.out.println("\nBelow is the input you entered"); System.out.println(yourInput); } catch (IOException ex) { System.out.println(Could not read from the keyboard } } // End of main method } // End of class ReadStringFromKeyboard Programming I ITP 120 Java Patrick Healy

181

Using Java I/O

Class #15 Input and Output


Example: Reading from an external file

public class ReadFromFile { public static void main(String[ ] args) { String st = null; File inputFileName = null; FileReader inputFile = null; BufferedReader in = null; try { inputFileName = new File("Input1.txt"); inputFile = new FileReader(inputFileName); in = new BufferedReader(inputFile); /* Note: The above 3 lines can be combined in one line as below in = new BufferedReader(new FileReader(new File("Input1.txt")));

*/

Patrick Healy

ITP 120 Java Programming I

182

Using Java I/O

Class #15 Input and Output


Example Continued
// Now let us start reading from the opened file while((st = br.readLine()) != null ) { System.out.println(st); // Print the string } } catch (FileNotFoundException fnex) { System.out.println(Error: + fnex.getMessage( ) ); System.out.println("Input file was not found"); } catch (IOException ex) { System.out.println(Error: + ex.getMessage( ) ); System.out.println("There was a problem reading from the file"); }

Patrick Healy

ITP 120 Java Programming I

183

Using Java I/O

Class #15 Input and Output

Example continued

finally { if( br != null) try { br.close( ); // Close the file } catch (Exception ex) { System.out.println(Error: + ex.getMessage( ) ); System.out.println("There was a problem with closing the file"); } } // End finally block } // End of main method } // End of class
Patrick Healy
ITP 120 Java Programming I
184

Class #15 Input and Output

Print Streams
The data output stream outputs a binary representation of data, so you cannot view its contents as text. In Java, you can use print streams to output data into files. These files can then be viewed as text. The PrintStream and PrintWriter classes provide the functionality for doing this.

PrintStream is for bytes PrintWriter is for characters (Unicode)

Patrick Healy

ITP 120 Java Programming I

185

Class #15 Input and Output

Print Streams: PrintWriter Constructors

PrintWriter(Writer out) PrintWriter(Writer out, boolean autoFlush) PrintWriter(OutputStream out) PrintWriter(OutputStream out, boolean autoFlush)

Patrick Healy

ITP 120 Java Programming I

186

Class #15 Input and Output

Print Streams: PrintWriter Methods (for chars)


void void void void void void void void void

print(Object o) print(String s) println(String s) print(char c) print(char[] cArray) print(int i) print(long l) print(float f) print(double d)

void print(boolean b)

Patrick Healy

ITP 120 Java Programming I

187

Print Streams: PrintWriter Methods

Class #15 Input and Output

Note:

On the previous slide, you may replace print with println in the various method definitions. The println method, which prints the object, is followed by a new line. When the object is passed to print or println, the objects toString( ) method converts it to a String object.

Patrick Healy

ITP 120 Java Programming I

188

Demo Program Example Using Print Streams

Class #15 Input and Output

The next sample Java program creates a print stream, pw, of PrintWriter, wrapped on FileOutputStream, for text format.
pw = new PrintWriter(new FileOutputStream(tempFile),true);

The program creates the file, arg[0], if that file does not already exist. The program writes 10 random integers into the file by using the data output stream, then closes the stream. The data file could be viewed by using the type command in DOS

Patrick Healy

ITP 120 Java Programming I

189

Using Print Streams: Demo Example


// TestPrintWriters.java: Create a text file // using PrintWriter import java.io.*; public class TestPrintWriters { // Main method: args[0] is the output file public static void main(String[] args) { // Declare print stream PrintWriter pw = null;

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

190

Using Print Streams: Demo example


// Check usage
if (args.length != 1) { System.out.println("Usage: java TestPrintWriters file"); System.exit(0); } File tempFile = new File(args[0]);

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

191

Using Print Streams: Demo Example


if (tempFile.exists())
{ System.out.println("The file " + args[0] + " already exists, delete it, rerun the program"); System.exit(0); }

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

192

Using Print Streams: Demo Example


// Write data
try { // Create print writer stream for tempFile pw = new PrintWriter(new FileOutputStream(tempFile), true); for (int i=0; i<10; i++) pw.print(" "+(int)(Math.random()*1000)); }

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

193

Using Print Streams: Demo Example


catch (IOException ex) { System.out.println(ex.getMessage()); } finally { // Close files if (pw != null) pw.close(); } } }
194

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

Using Print Streams: Demo Example


C:\test>java TestPrintWriters
Usage: java TestPrintWriters filename C:\test>java TestPrintWriters test.dat C:\test>type test.dat (Use the TYPE command to see data in file)

Class #15 Input and Output

567 915 7 23 677 455 402 997 290 549

Patrick Healy

ITP 120 Java Programming I

195

Class #15 Input and Output

Print Streams

PrintWriter program

FileOutputStream args[0]

Patrick Healy

ITP 120 Java Programming I

196

Using Java I/O

Class #15 Input and Output


Example: WriteToFile.java Writing text to external files

import java.io.File; import java.io.FileWriter; import java.io.PrintWriter;

import java.io.IOException;
public class WriteToFile { public WriteToFile( ) { } // Empty constructor

Patrick Healy

ITP 120 Java Programming I

197

Using Java I/O

Class #15 Input and Output

Example: WriteToFile.java (continued) public static void main (String[ ] args) { File outputFileName = null; PrintWriter outToFile = null;
try { outputFileName = new File("outFile1.txt"); outToFile = new PrintWriter( new FileWriter(outputFileName)); // Now we can start writing to file outToFile.println("This message is going to the output file"); outToFile.println("This will be line two in the output file"); outToFile.println("We can write the output file any time we want"); outToFile.flush( ); // Flush output file }
Patrick Healy
ITP 120 Java Programming I
198

Using Java I/O

Class #15 Input and Output

Example 18.6 catch (IOException ex) { System.out.println(Error: + ex.getMessage( ) ); System.out.println("There was a problem writing to the output file"); } finally { if ( outToFile != null ) outToFile.close( ); // Close output file } // End of finally block } // End of main method } // End of class WriteToFile

Patrick Healy

ITP 120 Java Programming I

199

Class #15 Input and Output

Buffered Streams in Java


Java introduces buffered streams that speed up input and output by reducing the number of reads and writes. In the case of input, a bunch of data is read all at once instead of one byte at a time. In the case of output, data are first cached into a buffer, then written all together to the file.

Using buffered streams is highly recommended.

Patrick Healy

ITP 120 Java Programming I

200

Class #15 Input and Output

Buffered Stream Constructors


BufferedInputStream (InputStream in) BufferedInputStream (InputStream in, int bufferSize) BufferedOutputStream (OutputStream in) BufferedOutputStream (OutputStream in, int bufferSize) BufferedReader(Reader in) BufferedReader(Reader in, int bufferSize) BufferedWriter(Writer out) BufferedWriter(Writer out, int bufferSize)

Patrick Healy

ITP 120 Java Programming I

201

Class #15 Input and Output


Demo Program: ViewFile.java (A Text Viewer program)

This case study writes a program that views a text file in a text area. The user enters a filename in a text field and clicks the View button; the file is then displayed in a text area.

Patrick Healy

ITP 120 Java Programming I

202

Buffered Streams in Java

Class #15 Input and Output

ViewFile program

// ViewFile.java: Read a text file and store it in a text area import java.awt.*; // Buffered I/O example (Demo program) import java.awt.event.*; import java.io.*; import javax.swing.*;
public class ViewFile extends MyFrameWithExitHandling implements ActionListener { // Button to view view private JButton jbtView = new JButton("View");

Patrick Healy

ITP 120 Java Programming I

203

Buffered Streams in Java

Class #15 Input and Output

ViewFile program

// Text field to receive file name private JTextField jtf = new JTextField(12); // Text area to display file private JTextArea jta = new JTextArea(); public static void main(String [ ] args) // Main method { ViewFile frame = new ViewFile(); frame.setTitle("View File Program in Java"); frame.setSize(400, 300); frame.setVisible(true); }

Patrick Healy

ITP 120 Java Programming I

204

Buffered Streams in Java

Class #15 Input and Output

ViewFile program

// Constructor public ViewFile() { // Panel p to hold a label, a text field, and a button Panel p = new Panel(); p.setLayout(new BorderLayout()); p.add(new Label("Filename"), BorderLayout.WEST); p.add(jtf, BorderLayout.CENTER); jtf.setBackground(Color.yellow); jtf.setForeground(Color.red); p.add(jbtView, BorderLayout.EAST);

Patrick Healy

ITP 120 Java Programming I

205

Buffered Streams in Java


// Add jtaFile to a scroll pane

Class #15 Input and Output

ViewFile program

JScrollPane jsp = new JScrollPane(jtaFile); // Add jsp and p to the frame getContentPane().add(jsp, BorderLayout.CENTER); getContentPane().add(p, BorderLayout.SOUTH); // Register listener jbtView.addActionListener(this); }

Patrick Healy

ITP 120 Java Programming I

206

Buffered Streams in Java

Class #15 Input and Output

ViewFile program

// Handle the "View" button public void actionPerformed(ActionEvent e) { if (e.getSource() == jbtView) showFile(); }

Patrick Healy

ITP 120 Java Programming I

207

Buffered Streams in Java


// Display the file in the text area
private void showFile() {

Class #15 Input and Output

ViewFile program

// Use a BufferedStream to read text from the file BufferedReader infile = null; // Get file name from the input text field at the bottom String filename = jtf.getText().trim(); String inLine;

Patrick Healy

ITP 120 Java Programming I

208

Buffered Streams in Java


try
{ // Create a buffered stream

Class #15 Input and Output

ViewFile program

infile = new BufferedReader(new FileReader(filename)); // Read a line inLine = infile.readLine(); boolean firstLine = true;

Patrick Healy

ITP 120 Java Programming I

209

Buffered Streams in Java

Class #15 Input and Output

ViewFile program

while (inLine != null) // Append the line to the text area { if (firstLine) { firstLine = false; jtaFile.append(inLine); } else { jta.append("\n" + inLine); } inLine = infile.readLine(); } } // End of try block

Patrick Healy

ITP 120 Java Programming I

210

Buffered Streams in Java

Class #15 Input and Output

ViewFile program

catch (FileNotFoundException ex)


{ System.out.println(Error: + ex.getMessage( ) ); System.out.println("File not found: " + filename); } catch (IOException ex) { System.out.println(ex.getMessage()); }

Patrick Healy

ITP 120 Java Programming I

211

Buffered Streams in Java


finally
{ try {

Class #15 Input and Output

ViewFile program

if (infile != null) infile.close( ); // Close input file


} catch (IOException ex) { System.out.println(Error: + ex.getMessage( )); } } // End of finally block } // End of method showFile() } // End of class ViewFile
Patrick Healy
ITP 120 Java Programming I
212

Buffered Streams in Java

Class #15 Input and Output

ViewFile program

Demostrate the ViewFile program by running: java ViewFile (at the command prompt)

Wait for Java window to appear. then type Comcast1.txt or the name of some text file in the text box at the bottom of the Java window. Look at the contents on the text file in the Java window.

Patrick Healy

ITP 120 Java Programming I

213

Text Input & Output on the Console


In previous chapters, you used text input and output with the System class. The System class, as you have already seen, contains 3 I/O objects: System.in, System.out, and System.err. The objects in, out and err are static variables.
The variable in is of InputStream type and out , err are of PrintStream type. (byte streams) These are the basic objects that all java programmers use to get input from the keyboard, send output to the screen, and display error messages.

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

214

Text Input & Output on the Console


To perform console output, you can use any of the methods for PrintStream in the System.out object.
To get input from the keyboard, you can use the following statements to read a string from the keyboard See next slide AND ALSO VIEW THE EXPANDED VERSION of MyInput.java which follows thereafter

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

215

Text Input & Output on the Console


BufferedReader br
= new BufferedReader(new InputStreamReader(System.in), 1); // Note: the 1 above means a buffer size of 1 // Declare and initialize the string String string = " "; // Get the string from the keyboard try { string = br.readLine(); { } System.out.println(ex); } catch (IOException ex)

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

216

Text I/O on the Console


{ // Read a string from the keyboard public static String readString() {

Class #15 Input and Output

MyInput.java (full)

public class MyInput // Expanded version

BufferedReader br
= new BufferedReader(new InputStreamReader(System.in), 1); // Declare and initialize the string String string = " "; // Get the string from the keyboard try { } { }
ITP 120 Java Programming I
217

string = br.readLine(); catch (IOException ex) System.out.println(ex) ;


Patrick Healy

Text I/O on the Console


return string; }

Class #15 Input and Output

MyInput.java (full)

// Return the string obtained from the keyboard

// Read an int value from the keyboard public static int readInt() { return Integer.parseInt(readString()); }

Patrick Healy

ITP 120 Java Programming I

218

Text I/O on the Console

Class #15 Input and Output

MyInput.java (full)

// Read a double value from the keyboard public static double readDouble() { return Double.parseDouble(readString()); }
// Read a byte value from the keyboard public static double readByte() { return Byte.parseByte(readString()); }

Patrick Healy

ITP 120 Java Programming I

219

Text I/O on the Console

Class #15 Input and Output

MyInput.java (full)

// Read a short value from the keyboard public static double readShort() { return Short.parseShort(readString()); }
// Read a long value from the keyboard public static double readLong() { return Long.parseLong(readString()); }

Patrick Healy

ITP 120 Java Programming I

220

Text I/O on the Console

Class #15 Input and Output

MyInput.java (full)

// Read a float value from the keyboard


public static double readFloat() { return Float.parseFloat(readString()); } }

Patrick Healy

ITP 120 Java Programming I

221

Random Access Files (byte streams)


Class #15 Input and Output

Java allows you to access the contents of a file in random order


To do this, you will use RandomAccessFile which encapsulates a random-access file. RandomAccessFile is a stream class derived from Object RandomAccessFile is NOT derived from InputStream or OutputStream. RandomAccessFile implements interfaces InputData & OutputData InputData & OutputData define the basic I/O methods. You can also position the file pointer within the file using the method seek ( )

Patrick Healy

ITP 120 Java Programming I

222

Random Access Files (Constructor(s))

Class #15 Input and Output

The constructor for RandomAccessFile is:


RandomAccessFile (String filename, String access) throws FileNotFoundException

The name of the file is passed in filename The term access determines what type of file access is permitted. If the access is r, the file is read-only. If the access is rw, the file is opened in read-write mode.

Patrick Healy

ITP 120 Java Programming I

223

Random Access Files (Methods)

Class #15 Input and Output

The method seek ( ) is used to set the current position of the file pointer within a random access file:
void seek (long newpos) throws IOException

newpos specifies the new position, in bytes, of the file pointer from the beginning of the file. After a call to seek( ), the next read or write operation will occur at the new file position.

Patrick Healy

ITP 120 Java Programming I

224

Random Access Files (Methods)

Class #15 Input and Output

public long getFilePointer ( ) throws IOException


Returns the offset, in bytes, from the beginning of the file to where the next read or write occurs.

public long length ( ) throws IOException Returns the length of the file in bytes. public final void writeChar (int v) throws IOException Writes a character to the file as a 2-byte Unicode character with the higher byte written first. public final void writeChars(String s) throws IOException Writes a string to a file as a sequence of characters.

Patrick Healy

ITP 120 Java Programming I

225

Random Access Files

Class #15 Input and Output

RandomAccessFile implements the read ( ) and write ( ) methods.


It also implements the InputData and OutputData interfaces, which means that methods to read and write the simple data types such as readInt( ) and writeDouble( ) are available. The slides which follow show a Java program that demonstrates random

access file I/O. The program writes 6 double numbers to a file and
then reads them back in a non-sequential order.

Patrick Healy

ITP 120 Java Programming I

226

Random Access Files


import java.io.*;

Class #15 Input and Output

// Demonstrate random access files

RandonAccessDemo.java

public class RandomAccessDemo { public static void main(String[ ] args) throws IOException { double data[ ] = { 19.4, 10.1, 123.54, 33.0, 87.9, 74.25 }; double d; RandomAccessFile raf;

Patrick Healy

ITP 120 Java Programming I

227

Random Access Files


try {

Class #15 Input and Output

raf = new RandomAccessFile("random.dat", "rw"); } catch(FileNotFoundException ex) { System.out.println("Cannot open file."); System.out.println(Error: + ex.getMessage( ) ); return ; }

Patrick Healy

ITP 120 Java Programming I

228

Random Access Files

Class #15 Input and Output

// Write values to the file. for (int i=0; i < data.length; i++) { try { raf.writeDouble(data[i]); } catch(IOException ex) { System.out.println(Error: + ex.getMessage( )); System.out.println("Error writing to file."); return ; } } // End of for loop

Patrick Healy

ITP 120 Java Programming I

229

Random Access Files


try {

Class #15 Input and Output

// Now, read back specific values raf.seek(0); // seek to first double

d = raf.readDouble();
System.out.println("First value is " + d); raf.seek(8); // seek to second double d = raf.readDouble(); System.out.println("Second value is " + d); raf.seek(8 * 3); // seek to fourth double d = raf.readDouble(); System.out.println("Fourth value is " + d); System.out.println();
Patrick Healy
ITP 120 Java Programming I
230

Random Access Files

Class #15 Input and Output

// Now, read every other value.


System.out.println("Here is every other value: "); for (int i=0; i < data.length; i+=2) { raf.seek(8 * i); // seek to ith double d = raf.readDouble(); System.out.print(d + " "); } // End of for loop } // End of try block

Patrick Healy

ITP 120 Java Programming I

231

Random Access Files


catch(IOException exc)
{

Class #15 Input and Output

System.out.println(Error: + exc.getMessage( ) ); System.out.println("Error seeking or reading."); } raf.close( ); // Close the file } // End of main ( ) } // End of class RandomAccessDemo

Patrick Healy

ITP 120 Java Programming I

232

Random Access Files

Class #15 Input and Output

Output from the previous Java program RandomAccessDemo:

First value is 19.4 Second value is 10.1 Fourth value is 33.0 Here is every other value: 19.4 123.54 87.9

Patrick Healy

ITP 120 Java Programming I

233

Class #15 Input and Output

Case Studies: Address Book

Now let us use RandomAccessFile to create a useful project for storing and viewing and address book. The user interface of the program is shown in Figure 16.24. The Add button stores a new address to the end of the file. The First, Next, Previous, and Last buttons retrieve the first, next, previous, and last addresses from the file, respectively.

Patrick Healy

ITP 120 Java Programming I

234

Class #15 Input and Output

Parsing Text Files


The StreamTokenizer class lets you take an input stream and parse it into words, which are known as tokens. The tokens are read one at a time. The following is the StreamTokenizer constructor:
StreamTokenizer st = StreamTokenizer(Reader is)

Patrick Healy

ITP 120 Java Programming I

235

Class #15 Input and Output


StreamTokenizer

Constants

TT_WORD The token is a word. TT_NUMBER The token is a number. TT_EOL

The end of the line has been read.

TT_EOF The end of the file has been read.

Patrick Healy

ITP 120 Java Programming I

236

Class #15 Input and Output


StreamTokenizer

Variables
(token type)

int ttype

Contains the current token type, which matches one of the constants listed on the preceding slide.

double nval Contains the value of the current token if that token is a number. String sval Contains a string that gives the characters of the current token if that token is a word.

Patrick Healy

ITP 120 Java Programming I

237

Class #15 Input and Output


StreamTokenizer

Methods
IOException

public int nextToken() throws

Parses the next token from the input stream of this StreamTokenizer. The type of the next token is returned in the ttype field. If ttype == TT_WORD, the token is stored in sval; if ttype == TT_NUMBER, the token is stored in nval.

Patrick Healy

ITP 120 Java Programming I

238

Class #15 Input and Output

Example : Demo program Using StreamTokenizer


Demo: ParsingTextFile.java
in.dat James 32 60 30 George 100 100 100 John 90 94 100 30% 30% 40% + out.dat James 39.6 George 100.0 John 95.2

Patrick Healy

ITP 120 Java Programming I

239

ParsingTextFile.java

Class #15 Input and Output

(Demo program)

// ParsingTextFile.java: ITP 120 // Process text file using StreamTokenizer Chapter 18 I/O import java.io.*;
public class ParsingTextFile { // Main method public static void main(String[] args) { // Declare file reader and writer character (2 bytes) streams FileReader frs = null; FileWriter fws = null; // Declare streamTokenizer StreamTokenizer in = null;

Patrick Healy

ITP 120 Java Programming I

240

ParsingTextFile.java
// Declare a print stream PrintWriter out = null;

Class #15 Input and Output

(Demo)

// For input file fields: student name, midterm1, // midterm2, and final exam score String sname = null; double midterm1 = 0; double midterm2 = 0; double finalScore = 0;
// Computed total score double total = 0; try { // Create file input and output streams frs = new FileReader("grades.dat"); fws = new FileWriter("gradesout.dat");

Patrick Healy

ITP 120 Java Programming I

241

ParsingTextFile.java

Class #15 Input and Output

(Demo)

// Create a stream tokenizer wrapping file input stream in = new StreamTokenizer(frs); out = new PrintWriter(fws); // Create PrintWriter object // Read first token in.nextToken(); // Process a record // TTs are Tokenizer constants while (in.ttype != in.TT_EOF) // TT_EOF means end of file { // Get student name if (in.ttype == in.TT_WORD) // TT_WORD means token is a word sname = in.sval; else System.out.println("Bad file format");
Patrick Healy
ITP 120 Java Programming I
242

ParsingTextFile.java

Class #15 Input and Output

(Demo)

// Get midterm1 if (in.nextToken() == in.TT_NUMBER) //TT_NUMBER means token is a number midterm1 = in.nval; else System.out.println("Bad file format"); // Get midterm2 score if (in.nextToken() == in.TT_NUMBER) midterm2 = in.nval; else System.out.println("Bad file format"); // Get final exam score if (in.nextToken() == in.TT_NUMBER) finalScore = in.nval;
Patrick Healy
ITP 120 Java Programming I
243

ParsingTextFile.java

Class #15 Input and Output

(Demo)

total = midterm1*0.3 + midterm2*0.3 + finalScore*0.4; out.println(sname + " " + total); in.nextToken( ); } } catch (FileNotFoundException ex) { System.out.println("Error: " + ex.getMessage()); System.out.println("File not found: in.dat"); } catch (IOException ex) { System.out.println(ex.getMessage()); }
Patrick Healy
ITP 120 Java Programming I
244

ParsingTextFile.java

Class #15 Input and Output

(Demo)

finally // Always execute finally block { try { if (frs != null) frs.close(); if (fws != null) fws.close(); } catch (IOException ex) { System.out.println(ex); } } System.out.println("To view input file, TYPE GRADES.DAT"); System.out.println("To view output file, TYPE GRADESOUT.DAT"); } // End of main method } // End of class

Patrick Healy

ITP 120 Java Programming I

245

Chapter 18 Demo Programs


ReadBytes.java
WriteDemo.java ShowFile.java CopyFile.java CompFile.java RWData.java RandomAccessDemo.java PrintWriterDemo.java ReadChars.java ReadLines.java CopyFileUsingByteStream.java

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

246

Chapter 18 Demo Programs


TestDataStreams.java
TestFileClass.java TestPrintWriters.java ViewFile.java (cute file viewer program) ParsingTextFile.java TestRandomAccessFile.java needs these class files: AddressBook.java FixedLengthStringIO.class

Class #15 Input and Output

Patrick Healy

ITP 120 Java Programming I

247

Chapter 18 Demo Programs


TestDataStream.java
TestFileClass.java TestFileReader.java TestFileStream.java

Class #15 Input and Output

TestFileWriter.java
TestObjectStreamForArray.java TestObjectInputStream.java TestObjectOutputStream.java AddressBook.java (with FixedLengthStringIO.java) Other created or required files: object.dat, temp.txt, student.dat

Patrick Healy

ITP 120 Java Programming I

248

Class #15 Input and Output

End of Presentation

Patrick Healy

ITP 120 Java Programming I

249