+ All Categories
Home > Documents > Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Date post: 25-Dec-2015
Category:
Upload: elaine-hopkins
View: 222 times
Download: 4 times
Share this document with a friend
Popular Tags:
64
Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1
Transcript
Page 1: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Input and OutputText and Binary I/O

Chapter 19

Introduction to Java Y.Daniel Liang 1

Page 2: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

File Input and OutputPrograms to run are in the FileIO folder:

1. ScannerDriver.java

2. ScannerFile.java ScannerTextfile.txt (input file) ScannerOutputfile.txt (output file)

3. Inventory.java (Driver) InventoryItem.java input file: inventory.txt

Introduction to Java Y.Daniel Liang 2

Page 3: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

File Input and OutputPrograms to run contd.4. TestPrint.java

5. TestPrintWriter.java Team #1 output file: pw.txt

6. TestFileStream Team #2

7. TestDataStream Team #3 output file: temp.dat

Introduction to Java Y.Daniel Liang 3

Page 4: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

File Input and OutputPrograms to run contd.

8. Copy.java Team #4

Welcome.java (source file) Temp. java (target file)

9. TestObjectStreamForArray Team #5

Introduction to Java Y.Daniel Liang 4

Page 5: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Objectives

•To understand how I/O is processed in Java

•To distinguish between text I/O and binary I/O

•To read data from the console using the Scanner class

•To read data from a file using the Scanner class

Introduction to Java Y.Daniel Liang 5

Page 6: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Objectives contd.

•To write data to a file using the PrintWriter class

•To read and write bytes using FileInput Stream and FileOutputStream

•To read and write primitive values and strings using DataInputStream/ DataOutPutStream

Introduction to Java Y.Daniel Liang 6

Page 7: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Objectives contd.

•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

To know how to serialize arrays

Introduction to Java Y.Daniel Liang 7

Page 8: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Input and Output

IntroductionData held in variables, arrays, and objects are

temporary. Data are lost when the program ceases processing

To save the data created during the life of the program, you must save the data in a file onto a disk, CD, or some other storage device .

Then the file can be transported and can be read later by other programs

Introduction to Java Y.Daniel Liang 8

Page 9: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

IntroductionRedirection of Input and Output

It is tedious to test programs by typing data in for every test run.

Testing is far easier if the program reads input from a file.

You can prepare the file once and reuse it for many tests.

The command line interfaces of most operating systems provide a way to link a file to the input of a program, as if all the characters in the file had actually been typed by the user .

Introduction to Java Y.Daniel Liang 9

Page 10: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

IntroductionRedirection of Input and Output example:

java ClassName < data.txt > output.txt

Use input redirection to avoid repetitive typing during testing.

Use output redirection to save your program output in a file.

Introduction to Java Y.Daniel Liang 10

Page 11: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction contd.

Data are stored in two basic formats: text and binary

Text file is represented in human-readable form

Examples of text files that you can read: Files that are created with a simple text exitor ,

such as Windows Vista NotePad, as well as Java

source code, and HTML Files

Introduction to Java Y.Daniel Liang 11

Page 12: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction contd.

Data stored in a binary file are represented in binary form. You cannot read binary files. The files are designed to be read by programs.

Binary files consists of a series of bits

Text file consist of a series of characters.

Introduction to Java Y.Daniel Liang 12

Page 13: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction contd.

The advantages of binary files are that:

1. They are more efficient to process than text files. Text I/O requires encoding and decoding whereas binary I/O does not.

2. Binary files are independent of the encoding scheme on the host machine and thus are portable.

Introduction to Java Y.Daniel Liang 13

Page 14: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

The Scanner class

The simplest tool for reading text files is the Scanner class.

Class java.util.Scanner

14

Page 15: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

to Get Input from the Console Using the Scanner Class

Run ScannerDriver program in the FileIO Folder

next(): reading a string. A string delimeter is a space nextByte(): reading an integer of the byte type

nextShort(): reading an integer of the short type

nextInt(): reading an integer of the int type

nextLong(): reading an integer of the long type

nextFloat(): reading a number of the float type

nextDouble(): reading number of the double type

15

Page 16: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

To Get Input from a text file Using the Scanner Class

Run ScannerFile Program in the FileIO Folder

The action of reading data from a file is called file input.

16

Page 17: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

To read text data from a disk file, we use the

FileReader and BufferedReader objects. • We first construct a FileReader object

with the name of the file•Then we associate a BufferedReader object to

the file.

•Then we read data, using the readLine method of the BufferedReader class.

•Finally, we convert the String to a primitive data type as necessary.

•Run Programs: InventoryItem (Driver) Inventory Use input file: inventory.txt

17

Page 18: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

Sample code for processing a text file:String file = “customer.txt”;String line;try{ FileReader fr = new FileReader (file);

BufferedReader inFile = new BufferedReader(fr);

line = inFile.readLine();

while(line != null && count < MAX) { tokenizer = new StringTokenizer(line);

name = tokenizer.nextToken();

18

Page 19: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

Cont’d.try{ custNumber = Long.parseLong (tokenizer. nextToken()); balance = Double.parseDouble(tokenizer. nextToken()); phone = tokenizer.nextToken(); custsArray[count++] = new Customer(name, custNumber, balance, phone); } // end inner try block catch (NumberFormatException e) { } line = inFile.readLine(); }// end while block inFile.close();

19

Page 20: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

PrintWriter is an object we use to generate an output text file.

PrintWriter supports only two output methods: printprintln (for print line)

Run program TestPrinterWriter output file: pw.txt

20

Page 21: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

Constructors of the PrintWriter

• PrintWriter(Writer out)

• PrintWriter(Writer out, boolean autoFlush)

• PrintWriter(OutputStream out)

• PrintWriter(OutputStream out, boolean autoFlush)

21

Page 22: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

PrintWriter Methods

Introduction to Java Y.Daniel Liang

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

22

Page 23: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

StreamsIn Java, all I/O is handled in streams. A stream is an abstraction of the continuous one-way flow of data. The program

receives data thru the input stream and sends data thru the output stream.

Any source of input or destination for output is called a stream.

Program

Output Stream

File

Input Stream

Introduction to Java Y.Daniel Liang 23Introduction to Java Y.Daniel Liang

Page 24: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 24

Streams

All streams except random-access file streams flow in only one direction; therefore if you want to input and output, you need two separate stream objects.

Streams are objects. Stream objects have methods that read and write data , flush the stream, close the stream, and count the number of bytes in the stream, etc.

Page 25: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 2525

Binary I/OText I/O requires encoding and decoding. The JVM converts a Unicode to a file specific encoding when writing a character and coverts a file specific encoding to a Unicode when reading a character.

Binary I/O does not require conversions. When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file, the exact byte in the file is returned.

Text I/O program

The Unicode of the character

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

Page 26: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 26

Binary I/O Classes

The design of the Java I/O classes is a good example of applying inheritance, where common methods are generalized in superclasses, and sub classes provide specialized methods.

See next slide. It list some of the classes for performing binary I/O.

InputStream is the root for binary input classes.

OutputStream is the root for binary output classes

Page 27: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

27Introduction to Java Y.Daniel Liang 27

Binary I/O Classes

InputStream

OutputStream

Object

ObjectOutputStream

FilterOutputStream

FileOutputStream

BufferedInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

Page 28: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Stream Classes 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.

The subclasses of InputStream/OutputStream are analogous to thesubclasses of Reader/Writer.

Introduction to Java Y.Daniel Liang 28

Page 29: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

To Read and Write Binary Data from /To a Disk File

FileInputStream and FileOutputStream- all methods in these classes are inherited from InputStream and OutputStream(java.io. FileInputStream and java.io.FileOutputStream )

Create a FileInputStream: FileInputStream inputStream = new FileInputStream inputStream ( “input.bin”);

To write Binary Data to a Disk File: FileOutputStream outputStream = new FileOutputStream outputStream ( “output.bin”);

29

Page 30: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 30

InputStreamjava.io.InputStream

int read(byte[] b) throws IOException abstract int read() throws IOException

void close() throws IOException

int available() throws IOException

long skip(long n) throws IOException

Note: The abstract InputStream class defines the methods for the input stream of bytes

Page 31: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 31

OutputStreamjava.io.OutputStream

abstract void write(int b) throws IOException

void write(byte[] b) throws IOException

void close() throws IOException

void flush() throws IOException

Note: The abstract OutputStream class defines the methods for the output stream of bytes.

Page 32: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 32

FileInputStream/FileOutputStream

FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses.

InputStream

OutputStream

Object

ObjectOutputStream

FilterOutputStream

FileOutputStream

BufferedInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

Page 33: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 33

FileInputStreamTo construct a FileInputStream, use the following constructors:

public FileInputStream(String filename)

public FileInputStream(File file)

A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file.

Page 34: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 34

FileOutputStreamTo 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 file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter.

Page 35: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 35

FileOutputStream

The program TestFileStream uses binary I/O to write ten bytes values from 1 to 10 to a file named temp.dat

TestFileStreamTestFileStream RunRun

Page 36: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 36

FilterInputStream/FilterOutputStream

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

When you need to process primitive numeric types, use DatInputStream and DataOutputStream to filter bytes.

InputStream

OutputStream

Object

ObjectOutputStream

FilterOutputStream

FileOutputStream

BufferedInputStream

DataInputStream

BufferedOutputStream

DataOutputStream

PrintStream

ObjectInputStream

FilterInputStream

FileInputStream

Page 37: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 37

DataInputStream/DataOutputStreamDataInputStream reads bytes from the stream and converts them into appropriate primitive type values or 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 38: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 38

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 39: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 39

DataOutputStreamDataOutputStream 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 bits of the argument v.

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

Writes a character (composed of two bytes) to the output 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 output stream, followed by the UTF representation of every character in the string s.

OutputStream

FilterOutputStream

DataOutputStream

+DataOutputStream( out: OutputStream)

Page 40: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 40

Characters and Strings in Binary I/O

A Unicode consists of two bytes. The writeChar(char c) method writes the Unicode of character c to the output.

The writeChars(String s) method writes the Unicode for each character in the string s to the output.

Page 41: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 4141

Characters and Strings in Binary I/O Why UTF-8? What is UTF-8?

UTF-8 (8-bit UCS/Unicode Transformation Format) is a coding scheme that allows systems to operate with both ASCII and Unicode efficiently. Most operating systems use ASCII.

Java uses Unicode. The ASCII character set is a subset of the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character.

Page 42: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 4242

Characters and Strings in Binary I/O Why UTF-8? What is UTF-8?

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 less than 0x7FF are coded in two bytes. Other Unicode values are coded in three bytes.

Page 43: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

Using DataInputStream/DataOutputStream

Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors:

public DataInputStream(InputStream instream)public DataOutputStream(OutputStream outstream)

 The statements given below create data streams. The first statement creates an input stream for file in.dat; the second statement creates an output stream for file out.dat.

DataInputStream infile = new DataInputStream(new FileInputStream("in.dat"));DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat"));

Page 44: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

Using DataInputStream/DataOutputStream

DataInputStream and DataOutputStream read and write data primitive types values and strings in a machine-independent fashion.

Thereby enabling you to write a data file on one machine and read it on another machine that has a different operating system or file structure.

An application uses a data output stream to write data that can later be read by a program using a data input stream.

Page 45: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang

Using DataInputStream/DataOutputStream

The TestDataStream program writes student names and scores to a file named temp.dat and reads the data back from the file.

TestDataStreamTestDataStream RunRun

Page 46: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 46

Checking End of File

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

Order and Format

See program TestDataStream

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

Page 47: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 4747

BufferedInputStream/BufferedOutputStreamReduces the number of reads and writes

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 the InputStream/OutputStream classes.

Page 48: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 48

Constructing BufferedInputStream/BufferedOutputStream

// Create a BufferedInputStream

public BufferedInputStream(InputStream in)

public BufferedInputStream(InputStream in, int bufferSize)

 

// Create a BufferedOutputStream

public BufferedOutputStream(OutputStream out)

public BufferedOutputStream(OutputStream out, int bufferSize)

Page 49: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 49

Constructing BufferedInputStream/BufferedOutputStream

Improve the performance of the TestDataStream program by adding buffers in the streams in lines 6-7 and 21-22, as follows:

DataOutputStream output = new DataOutputStream(

new BufferedOutputStream(new

FileOutputStream(“temp.dat”));

DataInputStream input = new DataInputStream( new BufferedInputStream(new FileInputStream(“temp.dat”));

 

Page 50: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 5050

Case Studies: Copy File

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

java Copy source target

 

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

Page 51: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 5151

Case Studies: Copy File

The program uses the File class to check whether the source file and the target file exist.

The program copies a Java source file to an identical Java file

CopyCopy RunRun

Page 52: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 52

Object I/ODataInputStream/DataOutputStream enables you to perform I/O for objects in addition to primitive type values and strings. 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

Optional

Page 53: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 53

ObjectInputStream

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

Page 54: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 54

ObjectOutputStream

ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.

java.io.ObjectOutput

+writeObject(o: Object): void

Writes an object.

java.io.OutputStream

java.io.ObjectOutputStream

+ObjectOutputStream(out: OutputStream)

java.io.DataOutput

ObjectStreamConstants

Page 55: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 55

Using Object StreamsYou may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors:

// Create an ObjectInputStream

public ObjectInputStream(InputStream in)

 

// Create an ObjectOutputStream

public ObjectOutputStream(OutputStream out)

TestObjectOutputStreamTestObjectOutputStream RunRun

TestObjectInputStreamTestObjectInputStream RunRun

Page 56: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 56

Object StreamsThe ObjectInputStream class can save entire object out to a disk, and the C class can read them back in.

Objects are saved in binary format; therefore, you use streams and not writers.For example, you can write a Bank Account object to a file:

BankAccount bk = new …; ObjectOutputStream out = new ObjectOutputStream ( new FileOutputStream(“bank.dat”));Out.writeObject(bk);

Page 57: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 57

Object StreamsUse Object streams to save and restore all instance fields of an object automatically.

When reading the object back in, you use the readObject method of the ObjectInputStream class. That method returns an Object reference, so you need to remember the types of the objects that you saved and use a cast:

ObjectInputStream in = new ObjectInputStream ( new FileInputStream(“bank.dat”));BankAccount bk = (BankAccount) in.readObject( );

The readObject method can throw a ClassNotFoundException-it is a checked exception, so you need to catch or declare it.

Page 58: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 58

The Serializable InterfaceNot 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 Serializable.

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.

public MyClass implements Serializable{

// Definition of the class

}

Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays.

Page 59: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 59

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.

Page 60: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 60

The transient Keyword, cont.Consider the following class: public class Foo 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 Foo class is serialized, only variable v1 is serialized. Variable v2 is not serialized because it is a static variable, and variable v3 is not serialized because it is marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.

Page 61: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 61

Serializing Arrays 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 16.12 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. Note : java.io.File implements Comparable and Serializable

TestObjectStreamForArrayTestObjectStreamForArray RunRun

Page 62: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 62

More about the Serializable InterfaceThe process of saving objects to a stream is called serialization because each object is assigned a serial number on the stream. If the same object is saved twice, only the serial number is written out the second time.

When the objects are read back in, duplicate serial numbers are restored as reference to the same object.

Why don’t all classes implement Serializable?For security reasons, some programmers may not want to serialize classes with confidential contents. Once a class is serializable, anyone can write its objects to disk and analyze the disk file.

There are also some classes that contain values that are meaningless once a program exists, such as operating–system-specific font descriptors.These values should not be serialized.

Page 63: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 63

Random Access FilesAll 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 writen to at random locations.

Page 64: Input and Output Text and Binary I/O Chapter 19 Introduction to Java Y.Daniel Liang 1.

Introduction to Java Y.Daniel Liang 64

RandomAccessFile

Creates a RandomAccessFile stream with the specified File object and mode.

Creates a RandomAccessFile stream with the specified file name string and mode.

Closes the stream and releases the resource associated with the stream.

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

Returns the length of this file.

Reads a byte of data from this file and returns –1 an the end of stream.

Reads up to b.length bytes of data from this file into an array of bytes.

Reads up to len bytes of data from this file into an array of bytes.

Sets the offset (in bytes specified in pos) from the beginning of the stream to where the next read or write occurs.

Sets a new length of this file.

Skips over n bytes of input discarding the skipped bytes.

Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.

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

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


Recommended