java io correcto

249
Chapter 19 Binary Input & Output Java I ITP 120 

Upload: razzy-nice-nice

Post on 07-Apr-2018

251 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 1/249

Chapter 19 

Binary Input & Output Java I ITP 120 

Page 2: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 2/249

ITP 120 Java Programming I2 

Patrick Healy

Class #15 – Input and OutputChapter 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).

Page 3: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 3/249

ITP 120 Java Programming I3 

Patrick Healy

Class #15 – Input and Output

Overview 

The  java.io.* package provides a library of classes to read and writevarious 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 convertedto another type of streams by chaining. Chaining a character stream

reader to a byte stream reader to read bytes on one end and producecharacters at the other end .

Page 4: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 4/249

ITP 120 Java Programming I4 

Patrick Healy

Class #15 – Input and Output

Overview --- Streams 

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

Program

Output Stream

File

Input Stream

Page 5: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 5/249ITP 120 Java Programming I5 

Patrick Healy

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.

Page 6: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 6/249ITP 120 Java Programming I6 

Patrick Healy

Class #15 – Input and Output

Byte Stream Classes (note: the word “stream” )  

 InputStream

OutputStream 

RandomAccessFile  

Object

PipeOutputStream

SequenceInputStream

StringBufferInputStream

ByteArrayOutputStream

ObjectOutputStream 

FilterOutputStream

FileOutputStream

PipedInputStream

PushBackInputStream

BufferedInputStream

LineNumberInputStream

DataInputStream

BufferedOutputStream

DataOutputStream 

PrintStream 

ObjectInputStream 

FilterInputStream

FileInputStream 

ByteArrayInputStream InputData

OutputData 

ObjectOutput 

ObjectInput 

Page 7: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 7/249ITP 120 Java Programming I7 

Patrick Healy

Class #15 – Input and OutputCharacter Stream Classes (Character = 2 bytes) 

Reader

Writer

StreamTokenizer

Object

PrintWriter

BufferedWriter

CharArrayWriter

PipedWriter

FilterWriter

PipedReader

LineNumberReader

FileReader

PushBackReader

FileWriter

StringWriter

StringReader

InputStreamReader

CharArrayReader

BufferedReader

FilterReader

OutputStreamWriter

Page 8: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 8/249

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, youneed to create objects using appropriate Java I/O classes.

Formatter output = new Formatter("temp.txt");

output.format("%s", "Java 101");

output.close();

Scanner input = new Scanner(new File("temp.txt"));

System.out.println(input.nextLine());

Program

Input object

created from an

input class 

Output objectcreated from an

output class 

Input stream

Output stream

File 

File 01011…1001 

11001…1011 

Page 9: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 9/249

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 byprograms. For example, the Java source programs are stored in textfiles and can be read by a text editor, but the Java classes are stored inbinary files and are read by the JVM. The advantage of binary files isthat they are more efficient to process than text files.

Although it is not technically precise and correct, you can imaginethat a text file consists of a sequence of characters and a binary fileconsists of a sequence of bits. For example, the decimal integer 199 isstored as the sequence of three characters: '1', '9', '9' in a text file andthe same integer is stored as a byte-type value C7 in a binary file,because decimal 199 equals to hex C7.

Page 10: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 10/249

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 filespecific 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

The Unicode of 

the characterEncoding/ 

Decoding

Binary I/O program

A byte is read/written(b)

(a)

e.g.

 "199" 

The encoding of the characteris stored in the file

0x31

e.g.

 199 00110111

00110001 00111001 00111001

0x39 0x39

0xC7

The same byte in the file

Page 11: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 11/249

Binary I/O Classes

 InputStream

OutputStream

Object

ObjectOutputStream

FilterOutputStream

FileOutputStream

BufferedInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

Page 12: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 12/249

 java.io.InputStream

+read(): int 

+read(b: byte[]): int

+read(b: byte[], off: int,

len: int): int

+available(): int

+close(): void

+skip(n: long): long

+markSupported(): boolean

+mark(readlimit: int): void

+reset(): void

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 theend 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 actualnumber of bytes skipped is returned.

Tests if this input stream supports the mark and reset methods.

Marks the current position in this input stream.

Repositions this stream to the position at the time the mark method was last

called on this input stream.

The value returned is a byte as an

int type.

InputStream

Page 13: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 13/249

The value is a byte as an int type.

OutputStream

 java.io.OutputStream

+write(int b): void 

+write(b: byte[]): void

+write(b: byte[], off: int,

len: int): void

+close(): void

+flush(): 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.

Writes b[off], b[off+1], …, b[off+len-1] into the output stream.

Closes this input stream and releases any system resources associated with thestream.

Flushes this output stream and forces any buffered output bytes to be written out.  

Page 14: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 14/249

FileInputStream/FileOutputStream 

FileInputStream/FileOutputStream

associates a binary input/outputstream with an external file. All themethods inFileInputStream/FileOuptputStrea

 

 InputStream

OutputStream

Object

ObjectOutputStream

FilterOutputStream

FileOutputStream

BufferedInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

Page 15: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 15/249

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 attemptto create a FileInputStream with a nonexistent file.

Page 16: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 16/249

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)

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

TestFileStream 

Run

Page 17: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 17/249

FilterInputStream/FilterOutputStream 

Filter streams are streams that filter bytes for some purpose. The basic byte input streamprovides 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 classenables you to read integers, doubles, and strings instead of bytes and characters.FilterInputStream and FilterOutputStream are the base classes for filtering data. When youneed to process primitive numeric types, use DatInputStream and DataOutputStream to filterbytes.

 InputStream

OutputStream

Object

ObjectOutputStream

FilterOutputStream

FileOutputStream

BufferedInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

Page 18: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 18/249

DataInputStream/DataOutputStream DataInputStream reads bytes from the stream andconverts them into appropriate primitive type valuesor strings.

 InputStream

OutputStream

Object

ObjectOutputStream

FilterOutputStream

FileOutputStream

BufferedInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

DataOutputStream converts primitive type values or

strings into bytes and output the bytes to the stream.

Page 19: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 19/249

DataInputStream 

DataInputStream extends FilterInputStream and

implements the DataInput interface.

 java.io.DataInput 

+readBoolean(): boolean

+readByte(): byte

+readChar(): char 

+readFloat(): float 

+readDouble(): float 

+readInt(): int 

+readLong(): long

+readShort(): short +readLine(): String

+readUTF(): String

Reads a Boolean from the input stream.

Reads a byte from the input stream.

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. 

 InputStream

FilterInputStream

DataInputStream

+DataInputStream(

in: InputStream) 

Page 20: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 20/249

DataOutputStream DataOutputStream extends FilterOutputStream and implements the

DataOutput interface.

 java.io.DataOutput 

+writeBoolean(b: Boolean): void 

+writeByte(v: int): void 

+writeBytes(s: String): void 

+writeChar(c: char): void 

+writeChars(s: String): void 

+writeFloat(v: float): void 

+writeDouble(v: float): void 

+writeInt(v: int): void 

+writeLong(v: long): void +writeShort(v: short): void 

+writeUTF(s: String): void 

Writes a Boolean to the output stream.

Writes to the output stream the eight low-order bitsof the argument v.

Writes the lower byte of the characters in a string tothe output stream.

Writes a character (composed of two bytes) to theoutput stream.

Writes every character in the string s, to the output

stream, in order, two bytes per character.

Writes a float value to the output stream.

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 outputstream, followed by the UTF representation of every character in the string s. 

OutputStream

FilterOutputStream

DataOutputStream

+DataOutputStream(out: OutputStream) 

Page 21: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 21/249

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 foreach 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 ASCIIand Unicode efficiently. Most operating systems use ASCII. Java usesUnicode. 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 torepresent an 8-bit ASCII character as a 16-bit Unicode character. The UTF-

8 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 lessthan 0x7FF are coded in two bytes. Other Unicode values are coded inthree bytes.

Page 22: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 22/249

Using DataInputStream/DataOutputStream

Data streams are used as wrappers on existing input and

output streams to filter data in the original stream. Theyare created using the following constructors:

public DataInputStream(InputStream instream)

public DataOutputStream(OutputStream outstream)

The statements given below create data streams. The firststatement creates an input stream for file in.dat; thesecond statement creates an output stream for file

out.dat.DataInputStream infile =

new DataInputStream(new FileInputStream("in.dat"));

DataOutputStream outfile =

new DataOut utStream new FileOut utStream "out.dat"

TestDataStream  Run

Page 23: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 23/249

Checking End of File

TIP: If you keep reading data at the end of a stream, anEOFException 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.

Order and Format

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

Page 24: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 24/249

BufferedInputStream/ 

BufferedOutputStream Using buffers to speed up I/O

 InputStream

OutputStream

Object

ObjectOutputStream

FilterOutputStream

FileOutputStream

BufferedInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

BufferedInputStream/BufferedOutputStream does not contain new methods. All

the methods BufferedInputStream/BufferedOutputStream are inherited from theInputStream/OutputStream classes. 

Constructing

Page 25: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 25/249

Constructing

BufferedInputStream/BufferedOutputStream

 // Create a BufferedInputStreampublic BufferedInputStream(InputStream in)

public BufferedInputStream(InputStream in, int bufferSize)

 // Create a BufferedOutputStream

public BufferedOutputStream(OutputStream out)

public BufferedOutputStream(OutputStreamr out, int

bufferSize)

Page 26: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 26/249

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-linearguments using the following command:

 java Copy source target

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

Obj t I/O

Optional

Page 27: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 27/249

Object I/O 

DataInputStream/DataOutputStream enables you to perform I/O for

primitive type values and strings. ObjectInputStream/ObjectOutputStreamenables you to perform I/O for objects in addition for primitive typevalues and strings.

 InputStream

OutputStream

Object

ObjectOutputStream

FilterOutputStream

FileOutputStream

BufferedInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

p

Obj tI tSt

Page 28: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 28/249

ObjectInputStream

ObjectInputStream extends InputStream and implementsObjectInput and ObjectStreamConstants. 

 java.io.ObjectInput  

+readObject(): Object  Reads an object.

 java.io.InputStream

 java.io.ObjectInputStream

+ObjectInputStream(in: InputStream) 

 java.io.DataInput 

ObjectStreamConstants 

Obj tO t tSt

Page 29: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 29/249

ObjectOutputStream

ObjectOutputStream extends OutputStream and implementsObjectOutput and ObjectStreamConstants. 

 java.io.ObjectOutput  

+writeObject(o: Object): void  Writes an object.

ava.io.OutputStream

 java.io.ObjectOutputStream

+ObjectOutputStream(out: OutputStream) 

 java.io.DataOutput 

ObjectStreamConstants 

U i Obj t St

Page 30: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 30/249

Using Object Streams 

You may wrap an

ObjectInputStream/ObjectOutputStream on anyInputStream/OutputStream using the following

constructors:

 // Create an ObjectInputStream

public ObjectInputStream(InputStream in)

 // Create an ObjectOutputStream

public ObjectOutputStream(OutputStream out)

TestObjectOutputStream  Run

TestObjectInputStream  Run

Random Access Files

Page 31: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 31/249

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 streamsare sequential files that cannot be updated without creating anew file. It is often necessary to modify files or to insert newrecords into files. Java provides the RandomAccessFile classto allow a file to be read from and write to at randomlocations.

RandomAccessFile

Page 32: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 32/249

RandomAccessFile

Creates a RandomAccessFile stream with the specified File object andmode.

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, startingat the current file pointer.

Writes len bytes from the specified byte array starting at offset off to

this file.

 DataInput   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

Fil P i

Page 33: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 33/249

File Pointer

A random access file consists of a sequence of bytes.

There is a special marker called file pointer that ispositioned at one of these bytes. A read or writeoperation 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 thefile, the file pointer moves forward to the next data. Forexample, if you read an int value using readInt(), theJVM reads four bytes from the file pointer and now the

file pointer is four bytes ahead of the previous location.

bytefile byte … byte byte byte byte byte … byte byte byte byte byte

file pointer

bytefile byte … byte byte byte byte byte … byte byte byte byte byte

file pointer

(A) Before readInt()

(B) Before readInt()

i M h d

Page 34: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 34/249

RandomAccessFile Methods

Many methods in RandomAccessFile are the same as those

in DataInputStream and DataOutputStream. Forexample, readInt(), readLong(), writeDouble(),readLine(), writeInt(), and writeLong() can be usedin data input stream or data output stream as well as inRandomAccessFile

streams.

M h d

Page 35: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 35/249

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. 

i M h d

Page 36: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 36/249

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 strin to the file as a se uence of 

R d A Fil C t t

Page 37: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 37/249

RandomAccessFile Constructor

RandomAccessFile raf =

new RandomAccessFile("test.dat", "rw");//allows read and write 

RandomAccessFile raf =

new RandomAccessFile("test.dat", "r");//read only 

Case Studies: Address BookOptional

Page 38: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 38/249

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 theprogram 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

Page 39: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 39/249

Fixed Length String I/O

Random access files are often used to process files of 

records. For convenience, fixed-length records areused in random access files so that a record can belocated 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.If a string is smaller than the maximum size, the rest of the string is padded with blanks.

Record 1 Record 2 Record n

Field1 Field 2 … Field k  

file

e.g.,

Student 1 Student 2 Student n

name street city state zip

FixedLengthStringIO 

Page 40: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 40/249

End of Presentation 

Binary Input & Output Chapter 18 

Class #15 – Input and Output

C Fil j

Page 41: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 41/249

ITP 120 Java Programming I41 

Patrick Healy

CopyFile.java 

CopyFile.java is a program that copies files. The user needs to provide a sourcefile 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 targetfile already exists, tell the user the file already exists.

Class #15 – Input and Output

Object I/O (optional)

Page 42: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 42/249

ITP 120 Java Programming I42 

Patrick Healy

Object I/O (optional)  

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

addition for primitive type values and strings.

 InputStream

OutputStream

Object

ObjectOutputStream

FilterOutputStream

FileOutputStream

BufferedInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

Class #15 – Input and Output

Page 43: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 43/249

ITP 120 Java Programming I43 

Patrick Healy

ObjectInputStream (optional) 

ObjectInputStream extends InputStream and implements ObjectInput and

ObjectStreamConstants. 

 java.io.ObjectInput  

+readObject(): Object  Reads an object.

 java.io.InputStream

 java.io.ObjectInputStream

+ObjectInputStream(in: InputStream) 

 java.io.DataInput 

ObjectStreamConstants 

Class #15 – Input and Output

Page 44: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 44/249

ITP 120 Java Programming I44 

Patrick Healy

ObjectOutputStream (optional) 

ObjectOutputStream extends OutputStream and implements ObjectOutput and

ObjectStreamConstants. 

 java.io.ObjectOutput  

+writeObject(o: Object): void  Writes an object.

ava.io.OutputStream

 java.io.ObjectOutputStream

+ObjectOutputStream(out: OutputStream) 

 java.io.DataOutput 

ObjectStreamConstants 

Class #15 – Input and Output

Using Object Streams (optional)

Page 45: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 45/249

ITP 120 Java Programming I45 

Patrick Healy

Using Object Streams (optional)  

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

// Create an ObjectInputStream

public ObjectInputStream(InputStream in)

// Create an ObjectOutputStream

public ObjectOutputStream(OutputStream out)

Demo:  TestObjectOutputStream.java

TestObjectInputStream.java

Class #15 – Input and Output

The Serializable Interface

Page 46: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 46/249

ITP 120 Java Programming I46 

Patrick Healy

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.

Class #15 – Input and Output

Page 47: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 47/249

ITP 120 Java Programming I47 

Patrick Healy

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.

Class #15 – Input and OutputThe transient Keyword, cont. 

Page 48: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 48/249

ITP 120 Java Programming I48 

Patrick Healy

Consider the following class:

 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 isserialized. Variable v2 is not serialized because it is a static variable, andvariable v3 is not serialized because it is marked transient. If v3 were notmarked transient, a java.io.NotSerializableException would occur.

Class #15 – Input and Output

Serializing Arrays (optional)

Page 49: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 49/249

ITP 120 Java Programming I49 

Patrick Healy

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

Class #15 – Input and Output

Random Access Files

Page 50: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 50/249

ITP 120 Java Programming I50 

Patrick Healy

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.

Class #15 – Input and OutputRandomAccessFile 

Page 51: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 51/249

ITP 120 Java Programming I51 

Patrick Healy

Creates a RandomAccessFile stream with the specified File object andmode.

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   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

Class #15 – Input and OutputFile Pointers 

Page 52: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 52/249

ITP 120 Java Programming I52 

Patrick Healy

A random access file consists of a sequence of bytes. There is a specialmarker 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 isopened, 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.

Class #15 – Input and OutputFile Pointers 

( i th i t 4 b t h d)

Page 53: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 53/249

ITP 120 Java Programming I53 

Patrick Healy

(moving the pointer 4 bytes ahead) 

bytefile byte … byte byte byte byte byte … byte byte byte byte byte

file pointer

bytefile byte … byte byte byte byte byte … byte byte byte byte byte

file pointer

(A) Before readInt()

(B) Before readInt()

Class #15 – Input and Output

R d A Fil Methods

Page 54: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 54/249

ITP 120 Java Programming I54 

Patrick Healy

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 inRandomAccessFile streams.

Class #15 – Input and OutputRandomAccessFile Methods, cont. 

Page 55: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 55/249

ITP 120 Java Programming I55 

Patrick Healy

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. 

Class #15 – Input and Output

RandomAccessFile Methods cont

Page 56: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 56/249

ITP 120 Java Programming I56 

Patrick Healy

RandomAccessFile Methods, cont. 

long length()IOException

Returns the length of the file. 

final void writeChar(int v) throwsIOException

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. 

Class #15 – Input and Output

RandomAccessFile Constructors

Page 57: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 57/249

ITP 120 Java Programming I57 

Patrick Healy

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) 

Case Study: Address Book 

Page 58: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 58/249

Now let us use RandomAccessFile to create a useful project for

storing and viewing and address book. The user interface of theprogram 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

Page 59: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 59/249

59

Chapter 18 Demo Programs

ReadBytes.java (skip) WriteData.javaWriteDemo.java ReadData.java

ShowFile.java

CopyFile.java CopyFileUsingByteStream.java

CompFile.java

RWData.java

RandomAccessDemo.java

PrintWriterDemo.javaReadChars.java or BuffReader.java

ReadLines.java (BufferedReader)

Chapter 18 Demo Programs

Page 60: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 60/249

60

Chapter 18 Demo Programs

TextFileScannerDemo.java Uses input file morestuff.txt 

HasNextLineDemo.java

Uses input file original.txt

and creates output file numbered.txt

BufferReaderDemo.java

Uses input file: buffer.txt

Chapter 18 Demo Programs

Page 61: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 61/249

61

Chapter 18 Demo Programs

TestDataStreams.javaTestFileClass.java

TestPrintWriters.java

ViewFile.java (GUI text file viewer program)

needs MyFrameWithExitHanding.java class fileParsingTextFile.java (needs grades.dat file)

(creates gradesout.dat)

TestRandomAccessFile.java

  AddressBook.java (creates file address.dat) needs FixedLengthStringIO.class file

Chapter 18 Demo Programs

Page 62: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 62/249

62

Chapter 18 Demo Programs

TestDataStream.javaTestFileReader.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)

Class #15 – Input and OutputChapter 18 Input / Output 

Page 63: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 63/249

ITP 120 Java Programming I63 

Patrick Healy

Optional: More on Java File I/O 

Chapter 18 Java I ITP 120 

Class #15 – Input and OutputChapter 18: More on Input and Output 

Stream Classes (byte & character streams)

Page 64: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 64/249

ITP 120 Java Programming I64 

Patrick Healy

Stream Classes (byte & character streams) Predefined Streams (System.in, System.out, System.err)

Processing External FilesData Streams

Print Streams

Buffered Streams

Text Input and Output on the Console

Random Access Files 

Class #15 – Input and OutputChapter 18 Input /Output Objectives 

Understand input & output streams and learn how to create them

Page 65: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 65/249

ITP 120 Java Programming I65 

Patrick Healy

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.

Class #15 – Input and OutputOverview 

The java io * package provides a library of classes to read and write

Page 66: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 66/249

ITP 120 Java Programming I66 

Patrick Healy

The  java.io.  package provides a library of classes to read and writevarious 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 convertedto another type of streams by chaining. Chaining a character streamreader to a byte stream reader to read bytes on one end and produce

characters at the other end .

Class #15 – Input and OutputOverview Streams 

In Java all Input/Output is handled by streams

Page 67: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 67/249

ITP 120 Java Programming I67 

Patrick Healy

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 getinput 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  

Class #15 – Input and OutputOverview --- Streams 

Page 68: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 68/249

ITP 120 Java Programming I68 

Patrick Healy

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

Program

Output Stream

File

Input Stream

Class #15 – Input and OutputOverview and Background 

The original version of Java defined only the byte stream but character

Page 69: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 69/249

ITP 120 Java Programming I69 

Patrick Healy

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 separateclass hierarchies of bytes and streams.

How is I/O Handled in Java?

Page 70: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 70/249

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.

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

output.close();

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

Output stream

File 

File 01011…1001 

11001…1011 

Class #15 – Input and OutputText Files vs. Binary Files  

Page 71: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 71/249

ITP 120 Java Programming I71 

Patrick Healy

Data stored in a text file are represented in human-readable form. Datastored 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 texteditor, but the Java classes are stored in binary files and are read by theJVM.

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 atext file consists of a sequence of characters and a binary file consists of asequence of bits. For example, the decimal integer 199 is stored as thesequence of three characters: '1', '9', '9' in a text file and the same integer isstored as a byte-type value C7 in a binary file, because decimal 199 equalsto hex C7 ( 12 x 16 + 7 = 192 + 7 = 199 decimal )

Binary I/O 

T I/O i di d d di Th JVM U i d

Page 72: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 72/249

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

The Unicode of 

the characterEncoding/ 

Decoding

Binary I/O program

A byte is read/written(b)

(a)

e.g.

 "199" 

The encoding of the character

is stored in the file

0x31

e.g.

 199 00110111

00110001 00111001 00111001

0x39 0x39

0xC7

The same byte in the file

Class #15 – Input and Output2 Types of Stream Classes: Bytes & Characters 

Page 73: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 73/249

ITP 120 Java Programming I73 

Patrick Healy

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.

Class #15 – Input and OutputByte Stream Classes (note: “stream” )  

D t I tStByteArrayInputStream

I tD t

Page 74: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 74/249

ITP 120 Java Programming I74 

Patrick Healy

 InputStream

OutputStream 

RandomAccessFile  

Object

PipeOutputStream

SequenceInputStream

StringBufferInputStream

ByteArrayOutputStream

ObjectOutputStream 

FilterOutputStream

FileOutputStream

PipedInputStream

PushBackInputStream

BufferedInputStream

LineNumberInputStream

DataInputStream

BufferedOutputStream

DataOutputStream 

PrintStream 

ObjectInputStream 

FilterInputStream

FileInputStream 

 InputData

OutputData 

ObjectOutput 

ObjectInput 

Class #15 – Input and OutputCharacter Stream Classes (Character = 2 bytes) 

CharArrayReader

Page 75: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 75/249

ITP 120 Java Programming I75 

Patrick Healy

Reader

Writer

StreamTokenizer

Object

PrintWriter

BufferedWriter

CharArrayWriter

PipedWriter

FilterWriter

PipedReader

LineNumberReader

FileReader

PushBackReader

FileWriter

StringWriter

StringReader

InputStreamReader

BufferedReader

FilterReader

OutputStreamWriter

Class #15 – Input and OutputPredefined Streams in Java 

All Java programs automatically import the java.lang package.

Page 76: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 76/249

ITP 120 Java Programming I76 

Patrick Healy

p g y p j g p g

The java.lang package defines a class called System whichencapsulates 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.

Class #15 – Input and OutputPredefined Streams in Java: System class 

System.in refers to the standard input stream which is the

Page 77: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 77/249

ITP 120 Java Programming I77 

Patrick Healy

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 theconsole by default. (Monitor)

These streams may be redirected to any compatible I/O device.

Class #15 – Input and OutputPredefined Streams in Java: System class 

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

Page 78: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 78/249

ITP 120 Java Programming I78 

Patrick Healy

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)

Class #15 – Input and OutputReading Keyboard Input 

 // Read an array of bytes from the keyboard.

i j i *

Page 79: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 79/249

ITP 120 Java Programming I79 

Patrick Healy

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

Class #15 – Input and OutputReading Keyboard Input 

Here is a sample run from the previous program:

Page 80: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 80/249

ITP 120 Java Programming I80 

Patrick Healy

Enter some characters: (prompt from program)READ BYTES (User entered READ BYTES)

 You entered: READ BYTES (output from program)

Class #15 – Input and OutputWriting Output to the Monitor 

 // Demonstrate System.out.write(). Java program WriteDemo.java

Page 81: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 81/249

ITP 120 Java Programming I81 

Patrick Healy

public class WriteDemo

{public static void main(String[ ] args)

{

int b;  // Program prints an „X‟ on the monitor  

b = 'X'; // The character is an intSystem.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 OutputStream classes (Bytes & Characters) 

The java.io package provides two categories of classes:B te stream readers and riters

Page 82: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 82/249

ITP 120 Java Programming I82 

Patrick Healy

Byte stream readers and writers Character stream readers and writers

At the top of the hierarchy for stream classes are the abstract classesInputStream 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 bythe classes that handle data, such as, int, double, char, etc., andobjects. Only ObjectInput specifies methods for reading objects.

DataInputStream - which is a subclass of FilterInputStream, which inturn is a subclass of InputStream – implements the InputData interface

and can read primitive data, and objects from byte streams.

Class #15 – Input and OutputStream Classes 

FileInputStream can read raw streams of data from files.

Page 83: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 83/249

ITP 120 Java Programming I83 

Patrick Healy

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.

Class #15 – Input and OutputInputStream Class (for reading bytes) 

Page 84: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 84/249

ITP 120 Java Programming I84 

Patrick Healy

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 therange of 0 to 255. At the end of the stream, itreturns a - 1.

 public int read(byte b[]) throws IOException

Reads bytes into array b,, returns b.length if thenumber of available bytes is >= b.length. Returnsthe number of bytes read if the number of available

 bytes is < than b.length, and returns –1 at the end 

of the stream.

Class #15 – Input and OutputInputStream Class (for reading bytes) 

Page 85: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 85/249

ITP 120 Java Programming I85 

Patrick Healy

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 IOExceptionReturns the number of bytes that can be read from the input stream without blocking.

Class #15 – Input and OutputInputStream Class (for reading bytes) 

Page 86: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 86/249

ITP 120 Java Programming I86 

Patrick Healy

The following method is defined in InputStream and isoften useful:

 public long skip(long n) throws IOException

Skip over and discard n bytes of data from theinput stream. The actual number of bytes skipped 

is returned.

Class #15 – Input and OutputReading & Writing Files Using Byte Streams 

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

FileOutputStream

Page 87: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 87/249

ITP 120 Java Programming I87 

Patrick Healy

FileOutputStream

To open a file, create an object of one of these classes, specifying thename 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.

Class #15 – Input and OutputReading & Writing Files Using Byte Streams 

 /* Display a text file.

T hi if h

Page 88: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 88/249

ITP 120 Java Programming I88 

Patrick Healy

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 */

 // Program ShowFile.java follows on the next slide ->

Class #15 – Input and OutputReading & Writing Files Using Byte Streams 

public class ShowFile {

public static void main(String[ ] args)

Page 89: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 89/249

ITP 120 Java Programming I89 

Patrick Healy

( g g )

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 OutputReading & Writing Files Using Byte Streams 

 // Read bytes until EOF is encountered

d {

Page 90: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 90/249

ITP 120 Java Programming I90 

Patrick Healy

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 OutputWriting to a File Using Byte Streams 

 /* Java program to Copy a text file.

T thi if th

Page 91: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 91/249

ITP 120 Java Programming I91 

Patrick Healy

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 OutputWriting to a File Using Byte Streams 

 // CopyFile.java Demo byte stream file operations

import java io *;

Page 92: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 92/249

ITP 120 Java Programming I92 

Patrick Healy

import java.io.*;

public class CopyFile {public static void main(String[ ] args) throws IOException

{

int i;

FileInputStream fin; // Declare 2 byte stream files (pointers)

FileOutputStream fout; // Output file pointer 

Class #15 – Input and OutputWriting to a File Using Byte Streams 

try { // outer try block

Page 93: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 93/249

ITP 120 Java Programming I93 

Patrick Healy

try { // outer try block

// 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; }

Class #15 – Input and OutputWriting to a File Using Byte Streams 

 // open output file

try {

Page 94: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 94/249

ITP 120 Java Programming I94 

Patrick Healy

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

Writing to a File Using Byte Streams 

catch(ArrayIndexOutOfBoundsException exc) {

System.out.println(“Error: “ + exc.getMessage( ) ); 

Page 95: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 95/249

ITP 120 Java Programming I95 

Patrick Healy

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

Class #15 – Input and Output

Reading & Writing Binary Data 

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

Page 96: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 96/249

ITP 120 Java Programming I96 

Patrick Healy

 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 Java‟s

simple data types to a file.

Class #15 – Input and Output

Reading & Writing Binary Data 

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

Page 97: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 97/249

ITP 120 Java Programming I97 

Patrick Healy

The constructor for DataOutputStream is:

DataOutputStream(OutputStream outputStream)

outputStream is the stream to which the binary data is written.

Class #15 – Input and Output

Reading & Writing Binary Data 

The constructor for DataInputStream is:

DataInputStream(InputStream inputStream)

Page 98: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 98/249

ITP 120 Java Programming I98 

Patrick Healy

DataInputStream(InputStream inputStream)

inputStream is the stream that is linked to the instance of 

DataInputStream being created.

DataInputStream implements the DataInput interface which providesthe methods for reading all of Java‟s simple data types. 

DataInputStream uses an InputStream instance as its foundation,

overlaying it with methods that read the various Java data types.

Class #15 – Input and Output

Reading & Writing Binary Data Examples 

To create an input stream for the file in.dat ( bytes)

Page 99: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 99/249

ITP 120 Java Programming I99 

Patrick Healy

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

Reading & Writing Binary Data 

Common Input Methods Defined by DataInputStream (a byte stream)

Input Method Purpose

Page 100: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 100/249

ITP 120 Java Programming I100 

Patrick Healy

Input Method Purpose

boolean readBoolean ( ) Reads a booleanbyte readByte ( ) Reads a byte

char readChar ( ) Reads a char 

double readDouble( ) Reads a double

float readFloat ( ) Reads a float

int readInt ( ) Reads an int

long readLong ( ) Reads a long

short readShort ( ) Reads a short

Class #15 – Input and Output

Reading & Writing Binary Data 

Common Output Methods Defined by DataOutputStream ( byte stream)

Output Method Purpose

Page 101: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 101/249

ITP 120 Java Programming I101 

Patrick Healy

p p

void writeBoolean (boolean val) writes the boolean specified by valvoid writeByte (int val) writes the low-order byte val

void writeChar(int val) writes the value val as a char 

void writeDouble(double val) writes the double val

void writeFloat(float val) writes the float val

void writeInt(int val) writes the int val

void writeLong(long val) writes the long val

void writeShort(int val) writes val as a short

Class #15 – Input and Output

Reading & Writing Binary Data 

Here is a Java program that demonstrates DataOutputStream and

DataInputStream. It writes and then reads back various types of data

Page 102: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 102/249

ITP 120 Java Programming I102 

Patrick Healy

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;

Class #15 – Input and Output

Reading & Writing Binary Data 

int i = 120;

double d = 1049.56;

Page 103: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 103/249

ITP 120 Java Programming I103 

Patrick Healy

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

Reading & Writing Binary Data 

try { // Write the binary data

System.out.println("Writing " + i);

dataOut writeInt(i);

Page 104: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 104/249

ITP 120 Java Programming I104 

Patrick Healy

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);

}

Class #15 – Input and Output

Reading & Writing Binary Data 

catch(IOException exc) {

System.out.println("Write error: + exc.getMessage( )");

}

Page 105: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 105/249

ITP 120 Java Programming I105 

Patrick Healy

}

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;

}

Class #15 – Input and Output

Reading & Writing Binary Data 

try { // Read the binary data

i = dataIn.readInt();

S t t i tl ("R di " i)

Page 106: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 106/249

ITP 120 Java Programming I106 

Patrick Healy

System.out.println("Reading " + i);

d = dataIn.readDouble();

System.out.println("Reading " + d);

b = dataIn.readBoolean();System.out.println("Reading " + b);

d = dataIn.readDouble();

System.out.println("Reading " + d);

}

Class #15 – Input and Output

Reading & Writing Binary Data 

catch(IOException exc) {

System.out.println("Read error.“ + exc.getMessage( ) ); } 

Page 107: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 107/249

ITP 120 Java Programming I107 

Patrick Healy

dataIn.close();} // End of main ( )

} // End of class RWData

The output from the previous program follows:

Writing 120 Reading 120

Writing 1023.56 Reading 1049.56

Writing true Reading true

Writing 90.28 Reading 90.28

Class #15 – Input and Output

Reader class methods for reading characters

The Reader class is similar to the InputStream class. The

Page 108: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 108/249

ITP 120 Java Programming I108 

Patrick Healy

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

Class #15 – Input and Output

OutputStream ( bytes) & Writer (for characters) 

Like InputStream (for reading bytes) and Reader (for reading

h ) O S d W i h

Page 109: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 109/249

ITP 120 Java Programming I109 

Patrick Healy

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 ->

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

Page 110: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 110/249

ITP 120 Java Programming I110 

Patrick Healy

 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 theoutput stream (for OutputStream) or characters inthe 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.

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

Page 111: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 111/249

ITP 120 Java Programming I111 

Patrick Healy

 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 theoutput stream (for OutputStream) or characters inthe 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.

Class #15 – Input and Output

Console Input using Character Streams 

For Java code that will be internationalized, inputting data from the

console using Java‟s character -based streams is a better, more

convenient way to read characters from the keyboard than using byte

Page 112: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 112/249

ITP 120 Java Programming I112 

Patrick Healy

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 whichsupports a buffered input stream. (BufferedReader inherits from

Reader)

But, you cannot construct a BufferedReader directly from System.in

Class #15 – Input and Output

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

Page 113: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 113/249

ITP 120 Java Programming I113 

Patrick Healy

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

Console Input using Character Streams 

Next, using the object produced by InputStreamReader, construct a

BufferedReader using the following constructor:

Page 114: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 114/249

ITP 120 Java Programming I114 

Patrick Healy

BufferedReader(Reader  inputReader )

Here, inputReader is the stream that is linked to the instance of 

BufferedReader being created.

Class #15 – Input and Output

Console Input using Character Streams 

Putting it all together, the following line of code creates a BufferReader 

that is connected to the keyboard.

Page 115: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 115/249

ITP 120 Java Programming I115 

Patrick Healy

BufferedReader br =

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)

Class #15 – Input and Output

Console Input using Character Streams 

Reading Characters

Characters can be read from System.in using the read( ) method

defined by BufferedReader

Page 116: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 116/249

ITP 120 Java Programming I116 

Patrick Healy

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

Class #15 – Input and Output

Console Input using Character Streams 

int read( ) throws IOException

reads a single Unicode character and returns a -1 when the end of thestream is reached.

Page 117: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 117/249

ITP 120 Java Programming I117 

Patrick Healy

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 bystart , storing up to max characters. It returns the number of charactersread or -1 when the end of the stream is reached.

Pressing the [Enter] key generates an end-of-stream condition. 

Class #15 – Input and Output

Console Input using Character Streams 

The following program demonstrates the read( ) method by reading

characters from the console until the user types a period.

Page 118: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 118/249

ITP 120 Java Programming I118 

Patrick Healy

 // Use a BufferedReader to read characters from the console.

import java.io.*;

public class ReadChars {

public static void main(String[ ] args) throws IOException{

Class #15 – Input and Output

Console Input using Character Streams 

BufferedReader br = new

BufferedReader(new InputStreamReader(System.in));

System out println("Enter some characters; period to quit ");

Page 119: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 119/249

ITP 120 Java Programming I119 

Patrick Healy

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

Console Input using Character Streams 

Output from the previous program could be:

Enter some characters; period to quit.

I

Page 120: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 120/249

ITP 120 Java Programming I120 

Patrick Healy

I

T

P

J

A

V

A

. <- note the period character which stopped the input stream

Class #15 – Input and Output

Console Input using Character Streams 

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:

Page 121: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 121/249

ITP 120 Java Programming I121 

Patrick Healy

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 returnsnull  if an attempt is made to read beyond the end of the stream.

Class #15 – Input and Output

Console Input using Character Streams 

The following program demonstrates BufferedReader and the readLine() method. The

program reads and displays lines of text until the user enters the word “stop” 

 // Read a string from console using a BufferedReader.

Page 122: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 122/249

ITP 120 Java Programming I122 

Patrick Healy

import java.io.*;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;

Page 123: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 123/249

Class #15 – Input and Output

Console Output using Character Streams 

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.

Page 124: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 124/249

ITP 120 Java Programming I124 

Patrick Healy

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)

Class #15 – Input and Output

Console Output using Character Streams 

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

Here outputStream is an object of type OutputStream

Page 125: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 125/249

ITP 120 Java Programming I125 

Patrick Healy

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.

If  flushOnNewLine is false, flushing is not automatic.

Class #15 – Input and Output

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( ).

Page 126: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 126/249

ITP 120 Java Programming I126 

Patrick Healy

For example, the following line of code creates a PrintWriter that isconnected 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

Console Output using Character Streams 

 // Demonstrate PrintWriter.

import java.io.*;

Page 127: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 127/249

ITP 120 Java Programming I127 

Patrick Healy

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

Console Output using Character Streams 

pw.println("Using a PrintWriter."); // PrintWriter Demo

pw.println(i);

pw.println(d);

Page 128: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 128/249

ITP 120 Java Programming I128 

Patrick Healy

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

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 

Page 129: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 129/249

ITP 120 Java Programming I129 

Patrick Healy

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.

Class #15 – Input and Output

File I / O using Character Streams FileWriter 

 // A simple keyboard-to-disk utility that demonstrates a FileWriter.

import java.io.*;

public class KtoD {

Page 130: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 130/249

ITP 120 Java Programming I130 

Patrick Healy

p {

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

File I / O using Character Streams FileWriter 

try {

fw = new FileWriter("test.txt"); // Try to open the file

}

Page 131: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 131/249

ITP 120 Java Programming I131 

Patrick Healy

}

catch(IOException exc) {

System.out.println(“Error: “ + exc.getMessage( ) ); 

System.out.println("Cannot open output file.");

return ;}

Class #15 – Input and Output

File I / O using Character Streams FileWriter 

System.out.println("Enter text ('stop' to quit).");

do {

System.out.print(": ");

Page 132: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 132/249

ITP 120 Java Programming I132 

Patrick Healy

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

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.

Page 133: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 133/249

ITP 120 Java Programming I133 

Patrick Healy

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

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.

Page 134: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 134/249

ITP 120 Java Programming I134 

Patrick Healy

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

File I / O using Character Streams FileReader 

while((s = br.readLine()) != null)

{

System.out.println(s);

Page 135: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 135/249

ITP 120 Java Programming I135 

Patrick Healy

}

fr.close( ); // Close the file

} // End of main( ) method

} // End of DtoS class

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

Page 136: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 136/249

ITP 120 Java Programming I136 

Patrick Healy

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 tounderstand how objects are serialized and what kind of objects can be serialized

To use RandomAccessFile for both read and write.

Class #15 – Input and Output

The File Class  

The File class is intended to provide an abstraction that deals

Page 137: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 137/249

ITP 120 Java Programming I137 

Patrick Healy

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 itsdirectory path.

Class #15 – Input and Output

 java.io.File

+File(pathname: String)

+File(parent: String, child: String)

+File(parent: File, child: String)

+exists(): boolean

+canRead(): boolean

+canWrite(): boolean

i Di t () b l

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

Creates a File object for the child under the directory parent. child may be a

filename or a subdirectory.

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.

Returns true if the file or the directory represented by the File object exists.

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.

R t t if th Fil bj t t di t

Obtaining file  properties and manipulating file  

Page 138: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 138/249

ITP 120 Java Programming I138 

Patrick Healy

+isDirectory(): boolean

+isFile(): boolean

+isAbsolute(): boolean

+isHidden(): boolean

+getAbsolutePath(): String

+getCanonicalPath(): String

+getName(): String

+getPath(): String

+getParent(): String

+lastModified(): long

+delete(): boolean

+renameTo(dest: File): Boolean

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 redundantnames, 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() returnstest.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, newFile("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.

Renames this file. The method returns true if the operation succeeds.

Class #15 – Input and Output

Example Using the File Class 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

f th Wi d d Fi 2 l

Page 139: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 139/249

ITP 120 Java Programming I139 

Patrick Healy

run of the program on Windows, and Figure 2 a sample run onUnix

(Windows) (Unix)

Class #15 – Input and Output

The File Class and Processing External Files 

The File class provides an abstraction that deals with most of the

machine-dependent complexities of files and path names in a machine-

independent fashion.

Page 140: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 140/249

ITP 120 Java Programming I140 

Patrick Healy

 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.

Class #15 – Input and Output

The File Class and Processing External Files 

 You can use the getName( ) method to get the name of the file.

For example,

if (myfile.exists( ) )

Page 141: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 141/249

ITP 120 Java Programming I141 

Patrick Healy

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”); 

Class #15 – Input and Output

The File Class and Processing External Files 

 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( ) )

Page 142: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 142/249

ITP 120 Java Programming I142 

Patrick Healy

if (myfile.exists( ) )

{

System.out.println(“The full path is “ + myfile.getPath( ) ); 

System.out.println(“The directory is “ + myfile.getParent( ) ); 

}

Class #15 – Input and Output

Demo Program: TestFileClass.java  // TestFileClass.java: Demonstrate the File class Chapt 18 I/O ITP120

import java.io.*;

import java.util.*;

public class TestFileClass {

bli i id i (S i [] ) {

Page 143: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 143/249

ITP 120 Java Programming I143 

Patrick Healy

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());

Class #15 – Input and Output

Demo Program: TestFileClass.java try {

System.out.println("What is its canonical path? " +

file.getCanonicalPath());

}

catch (IOException ex) { }

Page 144: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 144/249

ITP 120 Java Programming I144 

Patrick Healy

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

Processing External Files  

Again, you must use file streams to read from or write

to a disk file.

Page 145: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 145/249

ITP 120 Java Programming I145 

Patrick Healy

Once again, you can use FileInputStream or 

FileOutputStream for byte streams.

And you can use FileReader or FileWriter for character 

streams.

Class #15 – Input and Output

File I/O Stream Constructors  To create a file stream, use these constructors:

public FileInputStream (String filenameString) // Byte stream constructors

public FileInputStream (File file)

Page 146: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 146/249

ITP 120 Java Programming I146 

Patrick Healy

public FileOutputStream (String filenameString) // Byte stream constructor 

public FileOutputStream (File file)

public FileReader (String filenameString) // Character stream constructors

public FileReader (File file)

public FileWriter (String filenameString) // Character stream constructor 

public FileWriter (File file)

Class #15 – Input and Output

File I/O Stream Constructors  

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

Page 147: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 147/249

ITP 120 Java Programming I147 

Patrick Healy

FileInputStream infile = new FileInputStream("in.dat");

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

FileReader infile = new FileReader("in.dat");

FileWriter outfile = new FileWriter("out.dat");

Class #15 – Input and Output

Demo Program: TestFileReader.java  // TestFileReader.java Chapter 18 I/O ITP 120

import java.io.*;

public class TestFileReader {

public static void main(String[ ] args) {

Page 148: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 148/249

ITP 120 Java Programming I148 

Patrick Healy

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

Class #15 – Input and Output

Demo Program: TestFileReader.java System.out.println("File temp.txt does not exist");

}

catch (IOException ex) {

ex.printStackTrace();

}

Page 149: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 149/249

ITP 120 Java Programming I149 

Patrick Healy

}finally {

try {

input.close(); // Close the stream

}

catch (IOException ex) {ex.printStackTrace();

}

}

} // End of class TestFileReader 

Class #15 – Input and Output

Demo Program: TestFileWriter.java  // TestFileWriter.java Chapter 18 File I/O ITP 120

import java.io.*;

public class TestFileWriter {

public static void main(String[ ] args) throws IOException {

Page 150: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 150/249

ITP 120 Java Programming I150 

Patrick Healy

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();

}

}

Class #15 – Input and Output

Processing External Files 

FileInputStream fis [0]

Page 151: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 151/249

ITP 120 Java Programming I151 

Patrick Healy

FileInputStream fis

programargs[1]

args[0]

FileOutputStream fos

Class #15 – Input and Output

Processing External Files  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

Page 152: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 152/249

ITP 120 Java Programming I152 

Patrick Healy

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 

Class #15 – Input and Output

Processing External Files  // CopyFileUsingByteStream.java For Copying files (byte streams)

import java.io.*;

public class CopyFileUsingByteStream

{

Page 153: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 153/249

ITP 120 Java Programming I153 

Patrick Healy

{

 // 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;

Class #15 – Input and Output

Processing External Files 

if (args.length !=2) // args[0] is source file

{ // args[1] is target file

Page 154: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 154/249

ITP 120 Java Programming I154 

Patrick Healy

{ g [ ] gSystem.out.println(

"Usage: java CopyFileUsingByteStream f1 f2");

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

}

Class #15 – Input and Output

Processing External Files try

{

 // Create file input stream

fis = new FileInputStream(new File(args[0]));

Page 155: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 155/249

ITP 120 Java Programming I155 

Patrick Healy

 // 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;

}

Class #15 – Input and Output

Processing External Files else

fos = new FileOutputStream(args[1]); // FileOutputStream

 // Display the file size

Page 156: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 156/249

ITP 120 Java Programming I156 

Patrick Healy

p y

System.out.println("The file " + args[0] + " has "+

fis.available() + " bytes");

Class #15 – Input and Output

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

int r;

while ((r = fis.read()) != -1) // EOF is -1

fos.write((byte)r);

Page 157: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 157/249

ITP 120 Java Programming I157 

Patrick Healy

(( y ) );

}

catch (FileNotFoundException ex)

{

System.out.println(“Error: “ + ex.getMessage( ) ); 

System.out.println("File not found: " + args[0]);

}

Class #15 – Input and Output

Processing External Files catch (IOException ex)

{

System.out.println(“Some IO Exception occurred”); 

System.out.println(“Error: “ + ex.getMessage( )); 

Page 158: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 158/249

ITP 120 Java Programming I158 

Patrick Healy

y p ( g g ( ));

}

Continues to next slide 

Class #15 – Input and Output

Processing External Files finally

{

try

{

if (fis != null) fis.close(); // Close the input & output files

Page 159: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 159/249

ITP 120 Java Programming I159 

Patrick Healy

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

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.

Page 160: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 160/249

ITP 120 Java Programming I160 

Patrick Healy

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.

Class #15 – Input and Output

Filter Streams  To process strings, use BufferedReader and PushbackReader to filter 

characters.

Note: FilterInputStream and FilterOutputStream are abstract classes.

Page 161: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 161/249

ITP 120 Java Programming I161 

Patrick Healy

Class #15 – Input and Output

FilterInputStream subclasses  DataInputStream handles binary formats for all primitive data types.

BufferedInputStream gets data from the buffer and then reads them

from the stream if necessary.

Page 162: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 162/249

ITP 120 Java Programming I162 

Patrick Healy

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.

Class #15 – Input and Output

FilterOutputStream subclasses 

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

Page 163: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 163/249

ITP 120 Java Programming I163 

Patrick Healy

buffer to the stream.

PrintStream outputs the Unicode format of all primitive types which is

useful if the format is output to the console.

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.

Page 164: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 164/249

ITP 120 Java Programming I164 

Patrick Healy

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.

Class #15 – Input and OutputDataInputStream Methods defined in the DataInput

Interface 

int readByte() throws IOException

int readShort() throws IOException

int readInt() throws IOException

Page 165: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 165/249

ITP 120 Java Programming I165 

Patrick Healy

int readLong() throws IOException

float readFloat() throws IOException

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

 boolean readBoolean() throws IOException

String readUTF() throws IOException 

Class #15 – Input and OutputDataOutputStream 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

Page 166: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 166/249

ITP 120 Java Programming I166 

Patrick Healy

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

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.

Page 167: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 167/249

ITP 120 Java Programming I167 

Patrick Healy

DataInputStream infile = newDataInputStream(new FileInputStream("in.dat"));

The above creates an input file for in.dat.

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

The above creates an output file for out.dat.

Class #15 – Input and Output

Using Data Streams The next example shows a program that:

1) Creates 10 random integers,

2) Stores them in a data file,

Page 168: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 168/249

ITP 120 Java Programming I168 

Patrick Healy

3) Retrieves data from the file,

4) Displays the integers on the console.

See next slide  

Class #15 – Input and Output

Using Data Streams 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

Page 169: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 169/249

ITP 120 Java Programming I169 

Patrick Healy

{

 // Main method

public static void main(String[ ] args)

{

 // Declare data input and output streams

DataInputStream dis = null;

DataOutputStream dos = null;

Class #15 – Input and Output

Using Data Streams Demo Example  // Construct a temp file

File tempFile = new File("mytemp.dat");

 // Check if the temp file exists

if ( Fil i ())

Page 170: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 170/249

ITP 120 Java Programming I170 

Patrick Healy

if (tempFile.exists())

{

System.out.println("The file mytemp.dat already exists,"

+" delete it, rerun the program");

System.exit(0);

}

Class #15 – Input and Output

Using Data Streams Demo Example  // Write data

try

{

 // Create data output stream for tempFile

d D t O t tSt (

Page 171: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 171/249

ITP 120 Java Programming I171 

Patrick Healy

dos = new DataOutputStream(new

FileOutputStream(tempFile));

for (int i=0; i<10; i++)

dos.writeInt((int)(Math.random()*1000));

}

Class #15 – Input and Output

Using Data Streams Demo Example catch (IOException ex)

{

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

}

finally

Page 172: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 172/249

ITP 120 Java Programming I172 

Patrick Healy

{

try

{

if (dos != null) dos.close( ); // Close the file(s)

}

catch (IOException ex)

{ System.out.println(“Error: “ + ex.getMessage( ) ); } 

Class #15 – Input and Output

Using Data Streams Demo Example  // Read data

try

{

 // Create data input stream

di D t I tSt ( Fil I tSt (t Fil ))

Page 173: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 173/249

ITP 120 Java Programming I173 

Patrick Healy

dis = new DataInputStream(new FileInputStream(tempFile));

for (int i=0; i<10; i++)

System.out.print(" "+dis.readInt ( ) ); // Display the integers

}

Class #15 – Input and Output

Using Data Streams catch (FileNotFoundException ex)

{

System.out.println("File not found“ + ex.getMessage( ) );); 

}

catch (IOException ex)

Page 174: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 174/249

ITP 120 Java Programming I174 

Patrick Healy

catch (IOException ex)

{

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

}

Class #15 – Input and Output

Using Data Streams finally

{

try

{

if (dis != null) dis.close( ); // Close the file(s)

}

Page 175: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 175/249

ITP 120 Java Programming I175 

Patrick Healy

}

catch (IOException ex)

{

System.out.println(“Error: “ + ex.getMessage( ) )); 

}

} // End of finally block

} // End of main method

} // End of class TestDataStreams

Class #15 – Input and Output

Using Data Streams 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,

Page 176: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 176/249

ITP 120 Java Programming I176 

Patrick Healy

Program DataInputStream dis <-- fileInputStream <--mytemp.dat

DataOutputStream dos fileOutputStreammytemp.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.

Page 177: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 177/249

Class #15 – Input and Output

File Class 

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 Fil Obj t f t ith fil di t

Page 178: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 178/249

ITP 120 Java Programming I178 

Patrick Healy

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

Class #15 – Input and Output

File Class 

Example: DirectoryContents.java listing the contents of a directory using File class

import java.io.*;

public class DirectoryContents

{

public static void main(String[ ] args){

Page 179: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 179/249

ITP 120 Java Programming I179 

Patrick Healy

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

Class #15 – Input and Output

Using Java I/O 

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

Page 180: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 180/249

ITP 120 Java Programming I180 

Patrick Healy

BufferedReader in

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

 An InputStreamReader is like an adapter, it reads bytestreams and converts it into character streams

BufferedReader wraps the InputStreamReader to provide extrafunctionality, allowing to buffer the input to support readLine()

Class #15 – Input and Output

Using Java I/O 

Example Reading strings from the keyboard

Import java.io.*

public class ReadStringFromKeyboard {

public static void main(String[ ] args)

{ // Converts from bytes to charactersBufferedReader in = new BufferedReader(new InputStreamReader (System.in));

Page 181: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 181/249

ITP 120 Java Programming I181 

Patrick Healy

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

Class #15 – Input and Output

Using Java I/O 

Example: Reading from an external file

public class ReadFromFile {

public static void main(String[ ] args)

{

String st = null;

File inputFileName = null;

FileReader inputFile = null;

Page 182: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 182/249

ITP 120 Java Programming I182 

Patrick Healy

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"))); */

Class #15 – Input and Output

Using Java I/O 

Example Continued

 // Now let us start reading from the opened file

while((st = br.readLine()) != null )

{

System.out.println(st); // Print the string

}

}

Page 183: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 183/249

ITP 120 Java Programming I183 

Patrick Healy

}

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");

}

Class #15 – Input and Output

Using Java I/O 

Example continued

finally

{

if( br != null)

try {

br.close( ); // Close the file

Page 184: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 184/249

ITP 120 Java Programming I184 

Patrick Healy

}

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

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. Thesefiles can then be viewed as text.

Page 185: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 185/249

ITP 120 Java Programming I185 

Patrick Healy

The PrintStream and PrintWriter classes provide the

functionality for doing this. 

PrintStream is for bytes 

PrintWriter is for characters (Unicode)

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)

Page 186: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 186/249

ITP 120 Java Programming I186 

Patrick Healy

Class #15 – Input and Output

Print Streams:  PrintWriter  Methods (for chars) 

void print(Object o)

void print(String s)

void println(String s)

void print(char c)

void print(char[] cArray)

Page 187: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 187/249

ITP 120 Java Programming I187 

Patrick Healy

p y

void print(int i)

void print(long l)

void print(float f) void print(double d)

void print(boolean b) 

Class #15 – Input and Output

Print Streams:  PrintWriter  Methods 

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.

Page 188: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 188/249

ITP 120 Java Programming I188 

Patrick Healy

When the object is passed to print or  println,

the object‟s toString( ) method converts it to a String object.

Class #15 – Input and Output

Demo Program Example Using Print Streams 

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);

Page 189: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 189/249

ITP 120 Java Programming I189 

Patrick Healy

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

Class #15 – Input and Output

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

Page 190: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 190/249

ITP 120 Java Programming I190 

Patrick Healy

// 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

Using Print Streams: Demo example 

// Check usage

if (args.length != 1)

{

System.out.println("Usage: javaTestPrintWriters file");

Page 191: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 191/249

ITP 120 Java Programming I191 

Patrick Healy

System.exit(0);

}

File tempFile = new File(args[0]);

Class #15 – Input and Output

Using Print Streams: Demo Example 

if (tempFile.exists())

{

System.out.println("The file " + args[0] +

" already exists, delete it, rerun the program");

S t it(0)

Page 192: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 192/249

ITP 120 Java Programming I192 

Patrick Healy

System.exit(0);

}

Class #15 – Input and Output

Using Print Streams: Demo Example 

// Write data

try

{

// Create print writer stream for tempFile pw = new PrintWriter(new

Fil O t tSt (t Fil ) t )

Page 193: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 193/249

ITP 120 Java Programming I193 

Patrick Healy

FileOutputStream(tempFile), true);

for (int i=0; i<10; i++)

 pw.print(" "+(int)(Math.random()*1000));}

Class #15 – Input and Output

Using Print Streams: Demo Example 

catch (IOException ex)

{

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

}finally

{

Page 194: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 194/249

ITP 120 Java Programming I194 

Patrick Healy

{

// Close files

if (pw != null) pw.close();}

}

}

Class #15 – Input and Output

Using Print Streams: Demo Example 

C:\test>java TestPrintWriters

Usage: java TestPrintWriters filename

C:\test>java TestPrintWriters test.dat

Page 195: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 195/249

ITP 120 Java Programming I195 

Patrick Healy

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

567 915 7 23 677 455 402 997 290 549

Class #15 – Input and Output

Print Streams 

Page 196: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 196/249

ITP 120 Java Programming I196 

Patrick Healy

PrintWriter

program args[0]

FileOutputStream

Page 197: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 197/249

Class #15 – Input and Output

Using Java I/O 

Example: WriteToFile.java (continued)

public static void main (String[ ] args)

{

File outputFileName = null;

PrintWriter outToFile = null;

try {

Page 198: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 198/249

ITP 120 Java Programming I198 

Patrick Healy

outputFileName = new File("outFile1.txt");

outToFile = new PrintWriter( new FileWriter(outputFileName));

 // Now we can start writing to fileoutToFile.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

}

Class #15 – Input and Output

Using Java I/O 

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 {

Page 199: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 199/249

ITP 120 Java Programming I199 

Patrick Healy

y {

if ( outToFile != null )

outToFile.close( ); // Close output file

} // End of finally block

} // End of main method

} // End of class WriteToFile

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, thenwritten all together to the file.

Page 200: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 200/249

ITP 120 Java Programming I200 

Patrick Healy

Using buffered streams is highly recommended.

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)

Page 201: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 201/249

ITP 120 Java Programming I201 

Patrick Healy

BufferedReader(Reader in, int bufferSize)

BufferedWriter(Writer out)

BufferedWriter(Writer out, int bufferSize)

Class #15 – Input and OutputDemo 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.

Page 202: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 202/249

ITP 120 Java Programming I202 

Patrick Healy

Class #15 – Input and Output

Buffered Streams in Java 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.*;

Page 203: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 203/249

ITP 120 Java Programming I203 

Patrick Healy

public class ViewFile extends MyFrameWithExitHandling

implements ActionListener 

{

 // Button to view view

private JButton jbtView = new JButton("View");

Page 204: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 204/249

Class #15 – Input and Output

Buffered Streams in Java 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());

Page 205: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 205/249

ITP 120 Java Programming I205 

Patrick Healy

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);

Page 206: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 206/249

Class #15 – Input and Output

Buffered Streams in Java ViewFile program 

 // Handle the "View" button

public void actionPerformed(ActionEvent e){

if (e getSource() == jbtView)

Page 207: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 207/249

ITP 120 Java Programming I207 

Patrick Healy

if (e.getSource() jbtView)

showFile();

}

Class #15 – Input and Output

Buffered Streams in Java ViewFile program 

 // Display the file in the text area

private void showFile()

{

 // Use a BufferedStream to read text from the fileBufferedReader infile = null;

Page 208: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 208/249

ITP 120 Java Programming I208 

Patrick Healy

 // Get file name from the input text field at the bottom

String filename = jtf.getText().trim();

String inLine;

Class #15 – Input and Output

Buffered Streams in Java ViewFile program 

try

{

 // Create a buffered stream

infile = new BufferedReader(new FileReader(filename));

// Read a line

Page 209: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 209/249

ITP 120 Java Programming I209 

Patrick Healy

 // Read a line

inLine = infile.readLine();

boolean firstLine = true;

Class #15 – Input and Output

Buffered Streams in Java ViewFile program 

while (inLine != null) // Append the line to the text area

{

if (firstLine) {

firstLine = false;

 jtaFile.append(inLine); }

else

{

Page 210: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 210/249

ITP 120 Java Programming I210 

Patrick Healy

{

 jta.append("\n" + inLine); }

inLine = infile.readLine();

}

} // End of try block

Class #15 – Input and Output

Buffered Streams in Java ViewFile program 

catch (FileNotFoundException ex)

{ System.out.println(“Error: “ + ex.getMessage( ) ); 

System.out.println("File not found: " + filename);

}catch (IOException ex)

{

Page 211: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 211/249

ITP 120 Java Programming I211 

Patrick Healy

{

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

}

Class #15 – Input and Output

Buffered Streams in Java ViewFile program 

finally

{

try

{

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

}

catch (IOException ex)

Page 212: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 212/249

ITP 120 Java Programming I212 

Patrick Healy

{

System.out.println(“Error: “ + ex.getMessage( )); }

} // End of finally block

} // End of method showFile()

} // End of class ViewFile

Class #15 – Input and Output

Buffered Streams in Java ViewFile program 

Demostrate the ViewFile program by running:

 java ViewFile (at the command prompt)

Wait for Java window to appear.

Page 213: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 213/249

ITP 120 Java Programming I213 

Patrick Healy

pp

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.

Class #15 – Input and Output

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)

Page 214: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 214/249

ITP 120 Java Programming I214 

Patrick Healy

yp ( y )

These are the basic objects that all java programmers use to get inputfrom the keyboard, send output to the screen, and display error 

messages.

Class #15 – Input and Output

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

S t lid

Page 215: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 215/249

ITP 120 Java Programming I215 

Patrick Healy

See next slide   

AND ALSO VIEW THE EXPANDED VERSION of  MyInput.java which

follows thereafter 

Class #15 – Input and Output

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 

Page 216: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 216/249

ITP 120 Java Programming I216 

Patrick Healy

try 

{ string = br.readLine(); }

catch (IOException ex) { 

System.out.println(ex); }

Class #15 – Input and Output

Text I/O on the Console MyInput.java (full) 

 public class MyInput // Expanded version

{ // Read a string from the keyboard 

 public static String readString()

BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1);

 // Declare and initialize the string 

Page 217: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 217/249

ITP 120 Java Programming I217 

Patrick Healy

String string = " ";

 // Get the string from the keyboard 

try { 

string = br.readLine(); }

catch (IOException ex) { 

System.out.println(ex) ; }

Class #15 – Input and Output

Text I/O on the Console MyInput.java (full) 

 // Return the string obtained from the keyboard 

return string;

 }

 // Read an int value from the keyboard 

 public static int readInt()

Page 218: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 218/249

ITP 120 Java Programming I218 

Patrick Healy

return Integer.parseInt(readString());

 }

Page 219: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 219/249

Class #15 – Input and Output

Text I/O on the Console 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

Page 220: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 220/249

ITP 120 Java Programming I220 

Patrick Healy

 // Read a long value from the keyboard 

 public static double readLong()

return Long.parseLong(readString());

 }

Class #15 – Input and Output

Text I/O on the Console MyInput.java (full) 

 // Read a float value from the keyboard

public static double readFloat()

{

return Float.parseFloat(readString());}

}

Page 221: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 221/249

ITP 120 Java Programming I221 

Patrick Healy

Class #15 – Input and Output

Random Access Files (byte streams) 

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

Page 222: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 222/249

ITP 120 Java Programming I222 

Patrick Healy

InputData & OutputData define the basic I/O methods.

 You can also position the file pointer within the file using the methodseek ( )

Class #15 – Input and Output

Random Access Files (Constructor(s)) 

The constructor for RandomAccessFile is:

RandomAccessFile (String filename, String access)

throws FileNotFoundException

The name of the file is passed in filename

Page 223: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 223/249

ITP 120 Java Programming I223 

Patrick Healy

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.

Class #15 – Input and Output

Random Access Files (Methods) 

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

Page 224: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 224/249

ITP 120 Java Programming I224 

Patrick Healy

the beginning of the file.

After a call to seek( ), the next read or write operation will occur at the

new file position.

Class #15 – Input and Output

Random Access Files (Methods) 

 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

Page 225: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 225/249

ITP 120 Java Programming I225 

Patrick Healy

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.

Class #15 – Input and Output

Random Access Files 

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

Page 226: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 226/249

ITP 120 Java Programming I226 

Patrick Healy

p g

access file I/O. The program writes 6 double numbers to a file and

then reads them back in a non-sequential order.

Class #15 – Input and Output

Random Access Files 

 // Demonstrate random access files RandonAccessDemo.java

import java.io.*;

public class RandomAccessDemo {

public static void main(String[ ] args)

throws IOException {

Page 227: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 227/249

ITP 120 Java Programming I227 

Patrick Healy

double data[ ] = { 19.4, 10.1, 123.54, 33.0, 87.9, 74.25 };double d;

RandomAccessFile raf;

Class #15 – Input and Output

Random Access Files 

try {

raf = new RandomAccessFile("random.dat", "rw");

}

catch(FileNotFoundException ex)

{

System.out.println("Cannot open file.");

S t t i tl (“E “ + g tM g ( ) )

Page 228: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 228/249

ITP 120 Java Programming I228 

Patrick Healy

System.out.println(“Error: “ + ex.getMessage( ) ); 

return ;}

Class #15 – Input and Output

Random Access Files 

 // 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( )); 

Page 229: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 229/249

ITP 120 Java Programming I229 

Patrick Healy

System.out.println("Error writing to file.");

return ; }

} // End of “for” loop 

Class #15 – Input and Output

Random Access Files 

try {

 // 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();

Page 230: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 230/249

ITP 120 Java Programming I230 

Patrick Healy

d a ead oub e();

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();

Class #15 – Input and Output

Random Access Files 

 // 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

Page 231: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 231/249

ITP 120 Java Programming I231 

Patrick Healy

} // End of for loop 

} // End of try block

Class #15 – Input and Output

Random Access Files 

catch(IOException exc)

{

System.out.println(“Error: “ + exc.getMessage( ) ); 

System.out.println("Error seeking or reading.");

}

raf.close( ); // Close the file

} // End of main ( )

Page 232: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 232/249

ITP 120 Java Programming I232 

Patrick Healy

} // End of main ( )

} // End of class RandomAccessDemo

Class #15 – Input and Output

Random Access Files 

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:

Page 233: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 233/249

ITP 120 Java Programming I233 

Patrick Healy

Here is every other value:

19.4 123.54 87.9

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.

Page 234: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 234/249

ITP 120 Java Programming I234 

Patrick Healy

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 =

Page 235: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 235/249

ITP 120 Java Programming I235 

Patrick Healy

StreamTokenizer st =StreamTokenizer(Reader is)

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

Page 236: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 236/249

ITP 120 Java Programming I236 

Patrick Healy

TT_EOF 

The end of the file has been read.

Class #15 – Input and Output

StreamTokenizer Variables   int ttype (token type)

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

the preceding slide.

double nvalContains the value of the current token if that token is a number.

String sval

Contains a string that gives the

Page 237: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 237/249

ITP 120 Java Programming I237 

Patrick Healy

g g

characters of the current token if that

token is a word.

Class #15 – Input and Output

StreamTokenizer  Methods 

 public int nextToken() throws IOException

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;

Page 238: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 238/249

ITP 120 Java Programming I238 

Patrick Healy

_

if ttype == TT_NUMBER , the token is stored in nval.

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

out.dat

James 39.6

George 100.0

John 95.2

+

30%

30%

40%

Page 239: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 239/249

ITP 120 Java Programming I239 

Patrick Healy

Class #15 – Input and Output

ParsingTextFile.java (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

Page 240: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 240/249

ITP 120 Java Programming I240 

Patrick Healy

 // Declare file reader and writer character (2 bytes) streams

FileReader frs = null;FileWriter fws = null;

 // Declare streamTokenizer 

StreamTokenizer in = null;

Class #15 – Input and Output

ParsingTextFile.java (Demo) 

 // Declare a print stream

PrintWriter out = null;

 // 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;

Page 241: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 241/249

ITP 120 Java Programming I241 

Patrick Healy

;

try

{

 // Create file input and output streams

frs = new FileReader("grades.dat");

fws = new FileWriter("gradesout.dat");

Class #15 – Input and Output

ParsingTextFile.java (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

{

Page 242: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 242/249

ITP 120 Java Programming I242 

Patrick Healy

{

 // Get student nameif (in.ttype == in.TT_WORD) // TT_WORD means token is a word

sname = in.sval;

else

System.out.println("Bad file format");

Class #15 – Input and Output

ParsingTextFile.java (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

Page 243: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 243/249

ITP 120 Java Programming I243 

Patrick Healy

else

System.out.println("Bad file format");

 // Get final exam score

if (in.nextToken() == in.TT_NUMBER)

finalScore = in.nval;

Class #15 – Input and Output

ParsingTextFile.java (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");

Page 244: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 244/249

ITP 120 Java Programming I244 

Patrick Healy

System.out.println( File not found: in.dat );

}catch (IOException ex)

{

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

}

Class #15 – Input and Output

ParsingTextFile.java (Demo) 

finally // Always execute finally block{

try

{

if (frs != null) frs.close();

if (fws != null) fws.close();

}

catch (IOException ex)

{

System.out.println(ex);

}

Page 245: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 245/249

ITP 120 Java Programming I245 

Patrick Healy

}

}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

Class #15 – Input and Output

Chapter 18 Demo Programs 

ReadBytes.java

WriteDemo.java

ShowFile.java

CopyFile.java CopyFileUsingByteStream.java

CompFile.java

RWData.java

RandomAccessDemo.java

Page 246: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 246/249

ITP 120 Java Programming I246 

Patrick Healy

PrintWriterDemo.javaReadChars.java

ReadLines.java

Class #15 – Input and Output

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

Page 247: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 247/249

ITP 120 Java Programming I247 

Patrick Healy

FixedLengthStringIO.class

Class #15 – Input and Output

Chapter 18 Demo Programs 

TestDataStream.java

TestFileClass.java

TestFileReader.java

TestFileStream.java

TestFileWriter.javaTestObjectStreamForArray.java

TestObjectInputStream.java

TestObjectOutputStream.java

AddressBook java (with FixedLengthStringIO java)

Page 248: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 248/249

ITP 120 Java Programming I248 

Patrick Healy

AddressBook.java (with FixedLengthStringIO.java)

Other created or required files: object.dat, temp.txt, student.dat

Class #15 – Input and Output

End of Presentation 

Page 249: Java IO Correcto

8/3/2019 Java IO Correcto

http://slidepdf.com/reader/full/java-io-correcto 249/249

ITP 120 Java Programming I249 

Patrick Healy