Jedi Slides Intro2 Chapter12 Advanced Io Streams

Post on 19-May-2015

2.037 views 5 download

Tags:

Transcript of Jedi Slides Intro2 Chapter12 Advanced Io Streams

Introduction to Programming 2 1

12 Advanced I/O Streams

Introduction to Programming 2 2

Topics General Stream Types

Character and Byte Streams

Input and Output Streams

Node and Filter Streams

The File Class

Reader Classes Reader Methods

Node Reader Classes

Filter Reader Classes

Introduction to Programming 2 3

Topics Writer Classes

Writer Methods

Node Writer Classes

Filter Writer Classes

InputStream Classes InputStream Methods

Node InputStream Classes

Filter InputStream Classes

Introduction to Programming 2 4

Topics OutputStream Classes

OutputStream Methods

Node OutputStream Classes

Filter OutputStream Classes

Serialization The transient Keyword

Serialization: Writing an Object Stream

Deserialization: Reading an Object Stream

Introduction to Programming 2 5

General Stream Types Streams

Abstraction of a file or a device that allows a series of items to be read or written

General Stream Categories Character and Byte Streams

Input and Output Streams

Node and Filter Streams

Introduction to Programming 2 6

Character and Byte Streams Character streams

File or device abstractions for Unicode characters

Superclass of all classes for character streams: The Reader class The Writer class Both classes are abstract

Byte streams For binary data

Root classes for byte streams: The InputStream Class The OutputStream Class Both classes are abstract

Introduction to Programming 2 7

Input and Output Streams Input or source streams

Can read from these streams

Superclasses of all input streams: The InputStream Class The Reader Class

Output or sink streams Can write to these streams

Root classes of all output streams: The OutputStream Class The Writer Class

Introduction to Programming 2 8

Node and Filter Streams Node streams

Contain the basic functionality of reading or writing from a specific location

Types of node streams include files, memory and pipes

Filter streams Layered onto node streams between threads or processes

For additional functionalities

Adding layers to a node stream is called stream chaining

Introduction to Programming 2 9

The File Class Not a stream class

Important since stream classes manipulate File objects

Abstract representation of actual files and directory pathnames

Introduction to Programming 2 10

The File Class: Constructors Has four constructors

Introduction to Programming 2 11

The File Class: Methods

Introduction to Programming 2 12

The File Class: Methods

Introduction to Programming 2 13

The File Class: Example• import java.io.*;

• public class FileInfoClass {

• public static void main(String args[]) {

• String fileName = args[0];

• File fn = new File(fileName);

• System.out.println("Name: " + fn.getName());

• if (!fn.exists()) {

• System.out.println(fileName

• + " does not exists.");

• //continued...

Introduction to Programming 2 14

The File Class: Example• /* Create a temporary directory instead. */

• System.out.println("Creating temp

• directory...");

• fileName = "temp";

• fn = new File(fileName);

• fn.mkdir();

• System.out.println(fileName +

• (fn.exists()? "exists": "does not exist"));

• System.out.println("Deleting temp

• directory...");

• fn.delete();

• //continued...

Introduction to Programming 2 15

The File Class: Example• System.out.println(fileName +

• (fn.exists()? "exists": "does not exist"));

• return;

• } //end of: if (!fn.exists())

• System.out.println(fileName + " is a " +

• (fn.isFile()? "file." :"directory."));

• if (fn.isDirectory()) {

• String content[] = fn.list();

• System.out.println("The content of this

• directory:");

• //continued...

Introduction to Programming 2 16

The File Class: Example• for (int i = 0; i < content.length; i++) {

• System.out.println(content[i]);

• }

• } //end of: if (fn.isDirectory())

• if (!fn.canRead()) {

• System.out.println(fileName

• + " is not readable.");

• return;

• }

• //continued...

Introduction to Programming 2 17

The File Class: Example• System.out.println(fileName + " is " + fn.length()

• + " bytes long.");

• System.out.println(fileName + " is " +

• fn.lastModified() + " bytes long.");

• if (!fn.canWrite()) {

• System.out.println(fileName

• + " is not writable.");

• }

• }

• }

Introduction to Programming 2 18

The Reader Class: Methods

Introduction to Programming 2 19

The Reader Class: Methods

Introduction to Programming 2 20

Node Reader Classes

Introduction to Programming 2 21

Filter Reader Classes

Introduction to Programming 2 22

The Writer Class: Methods

Introduction to Programming 2 23

Node Writer Classes

Introduction to Programming 2 24

Filter Writer Classes

Introduction to Programming 2 25

Basic Reader/Writer Example• import java.io.*;

• class CopyFile {

• void copy(String input, String output) {

• FileReader reader;

• FileWriter writer;

• int data;

• try {

• reader = new FileReader(input);

• writer = new FileWriter(output);

• //continued...

Introduction to Programming 2 26

Basic Reader/Writer Example• while ((data = reader.read()) != -1) {

• writer.write(data);

• }

• reader.close();

• writer.close();

• } catch (IOException ie) {

• ie.printStackTrace();

• }

• }

• //continued...

Introduction to Programming 2 27

Basic Reader/Writer Example• public static void main(String args[]) {

• String inputFile = args[0];

• String outputFile = args[1];

• CopyFile cf = new CopyFile();

• cf.copy(inputFile, outputFile);

• }

• }

Introduction to Programming 2 28

Modified Reader/Writer Example

• import java.io.*;

• class CopyFile {

• void copy(String input, String output) {

• BufferedReader reader;

• BufferedWriter writer;

• String data;

• try {

• reader = new

• BufferedReader(new FileReader(input));

• writer = new

• BufferedWriter(new FileWriter(output));

• //continued...

Introduction to Programming 2 29

Modified Reader/Writer Example

• while ((data = reader.readLine()) != null) {

• writer.write(data, 0, data.length);

• }

• reader.close();

• writer.close();

• } catch (IOException ie) {

• ie.printStackTrace();

• }

• }

• //continued...

Introduction to Programming 2 30

Modified Reader/Writer Example

• public static void main(String args[]) {

• String inputFile = args[0];

• String outputFile = args[1];

• CopyFile cf = new CopyFile();

• cf.copy(inputFile, outputFile);

• }

• }

Introduction to Programming 2 31

The InputStream Class: Methods

Introduction to Programming 2 32

The InputStream Class: Methods

Introduction to Programming 2 33

Node InputStream Classes

Introduction to Programming 2 34

Filter InputStream Classes

Introduction to Programming 2 35

The OutputStream Class: Methods

Introduction to Programming 2 36

Node OutputStream Classes

Introduction to Programming 2 37

Filter OutputStream Classes

Introduction to Programming 2 38

Basic InputStream/ OutputStream Example

• import java.io.*;

• class CopyFile {

• void copy(String input, String output) {

• FileInputStream inputStr;

• FileOutputStream outputStr;

• int data;

• try {

• inputStr = new FileInputStream(input);

• outputStr = new FileOutputStream(output);

• //continued...

Introduction to Programming 2 39

Basic InputStream/ OutputStream Example

• while ((data = inputStr.read()) != -1) {

• outputStr.write(data);

• }

• inputStr.close();

• outputStr.close();

• } catch (IOException ie) {

• ie.printStackTrace();

• }

• }

• //continued...

Introduction to Programming 2 40

Basic InputStream/ OutputStream Example

• public static void main(String args[]) {

• String inputFile = args[0];

• String outputFile = args[1];

• CopyFile cf = new CopyFile();

• cf.copy(inputFile, outputFile);

• }

• }

Introduction to Programming 2 41

Modified InputStream/ OutputStream Example

• import java.io.*;

• class CopyFile {

• void copy(String input) {

• PushbackInputStream inputStr;

• PrintStream outputStr;

• int data;

• try {

• inputStr = new PushbackInputStream(new

• FileInputStream(input));

• outputStr = new PrintStream(System.out);

• //continued...

Introduction to Programming 2 42

Modified InputStream/ OutputStream Example

• while ((data = inputStr.read()) != -1) {

• outputStr.println("read data: " +

• (char) data);

• inputStr.unread(data);

• data = inputStr.read();

• outputStr.println("unread data: " +

• (char) data);

• }

• inputStr.close();

• outputStr.close();

• //continued...

Introduction to Programming 2 43

Modified InputStream/ OutputStream Example

• } catch (IOException ie) {

• ie.printStackTrace();

• }

• }

• public static void main(String args[]) {

• String inputFile = args[0];

• CopyFile cf = new CopyFile();

• cf.copy(inputFile);

• }

• }

Introduction to Programming 2 44

Serialization Definition:

Supported by the Java Virtual Machine (JVM)

Ability to read or write an object to a stream

Process of "flattening" an object

Goal: To save object to some permanent storage or to pass on to another object via the OutputStream class

Writing an object: Its state should be written in a serialized form such that the object

can be reconstructed as it is being read

Persistence Saving an object to some type of permanent storage

Introduction to Programming 2 45

Serialization Streams for serialization

ObjectInputStream For deserializing

ObjectOutputStream For serializing

To allow an object to be serializable: Its class should implement the Serializable interface

Its class should also provide a default constructor or a constructor with no arguments

Serializability is inherited Don't have to implement Serializable on every class Can just implement Serializable once along the class heirarchy

Introduction to Programming 2 46

Non-Serializable Objects When an object is serialized:

Only the object's data are preserved

Methods and constructors are not part of the serialized stream

Some objects are not serializable Because the data they represent constantly changes

Examples: FileInputStream objects Thread objects

A NotSerializableException is thrown if the serialization fails

Introduction to Programming 2 47

The transient Keyword A class containing a non-serializable object can still be

serialized Reference to non-serializable object is marked with the transient

keyword

Example:

• class MyClass implements Serializable {• transient Thread thread;• //try removing transient• int data;• /* some other data */• }

The transient keyword prevents the data from being serialized

Introduction to Programming 2 48

Serialization: Writing an Object Stream

Use the ObjectOutputStream class

Use its writeObject methodpublic final void writeObject(Object obj)

throws IOException

where, obj is the object to be written to the stream

Introduction to Programming 2 49

Serialization: Writing an Object Stream

• import java.io.*;

• public class SerializeBoolean {

• SerializeBoolean() {

• Boolean booleanData = new Boolean("true");

• try {

• FileOutputStream fos = new

• FileOutputStream("boolean.ser");

• ObjectOutputStream oos = new

• ObjectOutputStream(fos);

• oos.writeObject(booleanData);

• oos.close();

• //continued...

Introduction to Programming 2 50

Serialization: Writing an Object Stream

• } catch (IOException ie) {

• ie.printStackTrace();

• }

• }

• public static void main(String args[]) {

• SerializeBoolean sb = new SerializeBoolean();

• }

• }

Introduction to Programming 2 51

Deserialization: Reading an Object Stream

Use the ObjectInputStream class

Use its readObject methodpublic final Object readObject()

throws IOException, ClassNotFoundException

where, obj is the object to be read from the stream

The Object type returned should be typecasted to the appropriate class name before methods on that class can be executed

Introduction to Programming 2 52

Deserialization: Reading an Object Stream

• import java.io.*;

• public class UnserializeBoolean {

• UnserializeBoolean() {

• Boolean booleanData = null;

• try {

• FileInputStream fis = new

• FileInputStream("boolean.ser");

• ObjectInputStream ois = new

• ObjectInputStream(fis);

• booleanData = (Boolean) ois.readObject();

• ois.close();

• //continued...

Introduction to Programming 2 53

Deserialization: Reading an Object Stream

• } catch (Exception e) {

• e.printStackTrace();

• }

• System.out.println("Unserialized Boolean from "

• + "boolean.ser");

• System.out.println("Boolean data: " +

• booleanData);

• System.out.println("Compare data with true: " +

• booleanData.equals(new Boolean("true")));

• }

• //continued...

Introduction to Programming 2 54

Deserialization: Reading an Object Stream

• public static void main(String args[]) {

• UnserializeBoolean usb =

• new UnserializeBoolean();

• }

• }

Introduction to Programming 2 55

Summary General Stream Types

Character and Byte Streams

Input and Output Streams

Node and Filter Streams

The File Class Constructor

File(String pathname) Methods

Introduction to Programming 2 56

Summary Reader Classes

Methods read, close, mark, markSupported, reset

Node Reader Classes FileReader, CharArrayReader, StringReader, PipedReader

Filter Reader Classes BufferedReader, FilterReader, InputStreamReader,

LineNumberReader, PushbackReader

Introduction to Programming 2 57

Summary Writer Classes

Methods write, close, flush

Node Writer Classes FileWriter, CharArrayWriter, StringWriter, PipedWriter

Filter Writer Classes BufferedWriter, FilterWriter, OutputStreamWriter, PrintWriter

Introduction to Programming 2 58

Summary InputStream Classes

Methods read, close, mark, markSupported, reset

Node InputStream Classes FileInputStream, BufferedArrayInputStream, PipedInputStream

Filter InputStream Classes BufferedInputStream, FilterInputStream, ObjectInputStream, DataInputStream, LineNumberInputStream, PushbackInputStream

Introduction to Programming 2 59

Summary OutputStream Classes

Methods write, close, flush

Node OutputStream Classes FileOutputStream, BufferedArrayOutputStream, PipedOutputStream

Filter OutputStream Classes BufferedOutputStream, FilterOutputStream, ObjectOutputStream, DataOutputStream, PrintStream

Introduction to Programming 2 60

Summary Serialization

Definition

The transient Keyword

Serialization: Writing an Object Stream Use the ObjectOutputStream class Use its writeObject method

Deserialization: Reading an Object Stream Use the ObjectInputStream class Use its readObject method