SlideShare a Scribd company logo
12 Advanced I/O Streams
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
Topics Writer  Classes Writer  Methods Node  Writer  Classes Filter  Writer  Classes InputStream  Classes InputStream  Methods Node  InputStream  Classes Filter  InputStream  Classes
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
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
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
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
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
The  File  Class Not a stream class Important since stream classes manipulate  File  objects Abstract representation of actual files and directory pathnames
The  File  Class: Constructors Has four constructors
The  File  Class: Methods
The  File  Class: Methods
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...
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...
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...
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  + &quot; is not readable.&quot;); return; } //continued...
The  File  Class: Example System.out.println(fileName + &quot; is &quot; + fn.length() + &quot; bytes long.&quot;); System.out.println(fileName + &quot; is &quot; + fn.lastModified() + &quot; bytes long.&quot;); if (!fn.canWrite()) { System.out.println(fileName  + &quot; is not writable.&quot;); } } }
The  Reader  Class: Methods
The  Reader  Class: Methods
Node  Reader  Classes
Filter  Reader  Classes
The  Writer  Class: Methods
Node  Writer  Classes
Filter  Writer  Classes
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...
Basic  Reader / Writer  Example while ((data =  reader.read() ) != -1) { writer.write(data); } reader.close(); writer.close(); } catch (IOException ie) { ie.printStackTrace(); } } //continued...
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); } }
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...
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...
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); } }
The  InputStream  Class: Methods
The  InputStream  Class: Methods
Node  InputStream  Classes
Filter  InputStream  Classes
The  OutputStream  Class: Methods
Node  OutputStream  Classes
Filter  OutputStream  Classes
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...
Basic  InputStream /  OutputStream  Example while ((data =  inputStr.read() ) != -1) { outputStr.write(data); } inputStr.close(); outputStr.close(); } catch (IOException ie) { ie.printStackTrace(); } } //continued...
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); } }
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...
Modified  InputStream /  OutputStream  Example while ((data =  inputStr.read() ) != -1) { outputStr.println(&quot;read data: &quot; +  (char) data); inputStr.unread(data); data = inputStr.read(); outputStr.println(&quot;unread data: &quot; + (char) data); } inputStr.close(); outputStr.close(); //continued...
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); } }
Serialization Definition: Supported by the Java Virtual Machine (JVM) Ability to read or write an object to a stream Process of &quot;flattening&quot; 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
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
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
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
Serialization: Writing an Object Stream Use the  ObjectOutputStream  class Use its  writeObject  method public final void writeObject(Object obj) throws IOException where, obj  is the object to be written to the stream
Serialization: Writing an Object Stream import java.io.*; public class SerializeBoolean { SerializeBoolean() { Boolean booleanData = new Boolean(&quot;true&quot;); try { FileOutputStream fos = new  FileOutputStream(&quot;boolean.ser&quot;); ObjectOutputStream oos = new  ObjectOutputStream(fos); oos.writeObject(booleanData); oos.close(); //continued...
Serialization: Writing an Object Stream } catch (IOException ie) { ie.printStackTrace(); } } public static void main(String args[]) { SerializeBoolean sb = new SerializeBoolean(); } }
Deserialization: Reading an Object Stream Use the  ObjectInputStream  class Use its  readObject  method public 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
Deserialization: Reading an Object Stream import java.io.*; public class UnserializeBoolean { UnserializeBoolean() { Boolean booleanData = null; try { FileInputStream fis = new  FileInputStream(&quot;boolean.ser&quot;); ObjectInputStream ois = new  ObjectInputStream(fis); booleanData = (Boolean) ois.readObject(); ois.close(); //continued...
Deserialization: Reading an Object Stream } catch (Exception e) { e.printStackTrace(); } System.out.println(&quot;Unserialized Boolean from &quot;  + &quot;boolean.ser&quot;); System.out.println(&quot;Boolean data: &quot; +  booleanData ); System.out.println(&quot;Compare data with true: &quot; +  booleanData.equals(new Boolean(&quot;true&quot;)) ); } //continued...
Deserialization: Reading an Object Stream public static void main(String args[]) { UnserializeBoolean usb =  new UnserializeBoolean(); } }
Summary General Stream Types Character and Byte Streams Input and Output Streams Node and Filter Streams The  File  Class Constructor File(String pathname) Methods
Summary Reader  Classes Methods read ,  close ,  mark ,  markSupported ,  reset Node  Reader  Classes FileReader ,  CharArrayReader ,  StringReader ,  PipedReader Filter  Reader  Classes BufferedReader ,  FilterReader ,  InputStreamReader , LineNumberReader ,  PushbackReader
Summary Writer  Classes Methods write ,  close ,  flush Node  Writer  Classes FileWriter ,  CharArrayWriter ,  StringWriter ,  PipedWriter Filter  Writer  Classes BufferedWriter ,  FilterWriter ,  OutputStreamWriter ,  PrintWriter
Summary InputStream  Classes Methods read ,  close ,  mark ,  markSupported ,  reset Node  InputStream  Classes FileInputStream ,  BufferedArrayInputStream ,  PipedInputStream Filter  InputStream  Classes BufferedInputStream ,  FilterInputStream ,  ObjectInputStream ,  DataInputStream ,  LineNumberInputStream ,  PushbackInputStream
Summary OutputStream  Classes Methods write ,  close ,  flush Node  OutputStream  Classes FileOutputStream ,  BufferedArrayOutputStream ,  PipedOutputStream Filter  OutputStream  Classes BufferedOutputStream ,  FilterOutputStream ,  ObjectOutputStream ,  DataOutputStream ,  PrintStream
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

More Related Content

PDF
Java - File Input Output Concepts
ODP
IO In Java
PPT
Chapter 12 - File Input and Output
PDF
PPTX
Understanding java streams
PPT
Java stream
PPTX
Java Input Output (java.io.*)
PPT
File Input & Output
Java - File Input Output Concepts
IO In Java
Chapter 12 - File Input and Output
Understanding java streams
Java stream
Java Input Output (java.io.*)
File Input & Output

What's hot (20)

PPT
Java Streams
PDF
Java I/o streams
PPTX
L21 io streams
PDF
Java IO
PDF
32.java input-output
PDF
Java Course 8: I/O, Files and Streams
PPT
Java Input Output and File Handling
PPT
Input output streams
PPTX
Handling I/O in Java
PDF
java.io - streams and files
PPTX
Java file
PPTX
Input/Output Exploring java.io
PPT
IO and serialization
PPS
Files & IO in Java
PPTX
Java program file I/O
PDF
input/ output in java
PDF
Javaiostream
PPT
Byte stream classes.49
PPT
Java IO Package and Streams
PPTX
Java I/O
Java Streams
Java I/o streams
L21 io streams
Java IO
32.java input-output
Java Course 8: I/O, Files and Streams
Java Input Output and File Handling
Input output streams
Handling I/O in Java
java.io - streams and files
Java file
Input/Output Exploring java.io
IO and serialization
Files & IO in Java
Java program file I/O
input/ output in java
Javaiostream
Byte stream classes.49
Java IO Package and Streams
Java I/O
Ad

Similar to Jedi Slides Intro2 Chapter12 Advanced Io Streams (20)

PDF
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
PDF
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
PDF
Java Day-6
PPTX
Files io
PPT
Md121 streams
PPTX
File Input and output.pptx
PPTX
Input & output
PDF
Programming language JAVA Input output opearations
PDF
inputoutputstreams-140612032817-phpapp02.pdf
PDF
Java IO Stream, the introduction to Streams
PDF
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
PPTX
Input output files in java
PDF
CSE3146-ADV JAVA M2.pdf
PPT
Java Basics
PPT
Java căn bản - Chapter12
PPT
Iostreams
PDF
IO Streams, Serialization, de-serialization, autoboxing
PPTX
IO Programming.pptx all informatiyon ppt
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Java Day-6
Files io
Md121 streams
File Input and output.pptx
Input & output
Programming language JAVA Input output opearations
inputoutputstreams-140612032817-phpapp02.pdf
Java IO Stream, the introduction to Streams
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Input output files in java
CSE3146-ADV JAVA M2.pdf
Java Basics
Java căn bản - Chapter12
Iostreams
IO Streams, Serialization, de-serialization, autoboxing
IO Programming.pptx all informatiyon ppt
Ad

More from Don Bosco BSIT (20)

PPTX
Probability and statistics (frequency distributions)
PPTX
Probability and statistics (basic statistical concepts)
PPTX
Factors in assembling personal computer
PDF
Alumni response
PDF
Summative Report: 1st Consultative Curriculum Dev Oct. 20-21
PDF
8085 op codes
PPT
Data communication basics
ODP
Data communication basics
ODT
Research Primer
PDF
Os Virtualization
PPT
SYSAD323 Virtualization Basics
PDF
Shell Scripting Structured Commands
PDF
V Communication Error Detection And Correction
PDF
Iv The Telephone And Multiplex Systems
PDF
Iii Data Transmission Fundamentals
PDF
Ii Communications Channel
PDF
I Introduction To Data Communications
PPT
Secondary Storage Device Magnetic Tapes
PPT
Lecture #1 Introduction
PPT
Fundamental File Processing Operations
Probability and statistics (frequency distributions)
Probability and statistics (basic statistical concepts)
Factors in assembling personal computer
Alumni response
Summative Report: 1st Consultative Curriculum Dev Oct. 20-21
8085 op codes
Data communication basics
Data communication basics
Research Primer
Os Virtualization
SYSAD323 Virtualization Basics
Shell Scripting Structured Commands
V Communication Error Detection And Correction
Iv The Telephone And Multiplex Systems
Iii Data Transmission Fundamentals
Ii Communications Channel
I Introduction To Data Communications
Secondary Storage Device Magnetic Tapes
Lecture #1 Introduction
Fundamental File Processing Operations

Recently uploaded (20)

PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Classroom Observation Tools for Teachers
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
master seminar digital applications in india
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
O5-L3 Freight Transport Ops (International) V1.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Classroom Observation Tools for Teachers
human mycosis Human fungal infections are called human mycosis..pptx
Anesthesia in Laparoscopic Surgery in India
Week 4 Term 3 Study Techniques revisited.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
VCE English Exam - Section C Student Revision Booklet
master seminar digital applications in india
STATICS OF THE RIGID BODIES Hibbelers.pdf
Basic Mud Logging Guide for educational purpose
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
102 student loan defaulters named and shamed – Is someone you know on the list?
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Renaissance Architecture: A Journey from Faith to Humanism
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Microbial diseases, their pathogenesis and prophylaxis

Jedi Slides Intro2 Chapter12 Advanced Io Streams

  • 1. 12 Advanced I/O Streams
  • 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
  • 3. Topics Writer Classes Writer Methods Node Writer Classes Filter Writer Classes InputStream Classes InputStream Methods Node InputStream Classes Filter InputStream Classes
  • 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
  • 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
  • 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
  • 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
  • 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
  • 9. The File Class Not a stream class Important since stream classes manipulate File objects Abstract representation of actual files and directory pathnames
  • 10. The File Class: Constructors Has four constructors
  • 11. The File Class: Methods
  • 12. The File Class: Methods
  • 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(&quot;Name: &quot; + fn.getName()); if (!fn.exists()) { System.out.println(fileName + &quot; does not exists.&quot;); //continued...
  • 14. The File Class: Example /* Create a temporary directory instead. */ System.out.println(&quot;Creating temp directory...&quot;); fileName = &quot;temp&quot;; fn = new File(fileName); fn.mkdir(); System.out.println(fileName + (fn.exists()? &quot;exists&quot;: &quot;does not exist&quot;)); System.out.println(&quot;Deleting temp directory...&quot;); fn.delete(); //continued...
  • 15. The File Class: Example System.out.println(fileName + (fn.exists()? &quot;exists&quot;: &quot;does not exist&quot;)); return; } //end of: if (!fn.exists()) System.out.println(fileName + &quot; is a &quot; + (fn.isFile()? &quot;file.&quot; :&quot;directory.&quot;)); if (fn.isDirectory()) { String content[] = fn.list(); System.out.println(&quot;The content of this directory:&quot;); //continued...
  • 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 + &quot; is not readable.&quot;); return; } //continued...
  • 17. The File Class: Example System.out.println(fileName + &quot; is &quot; + fn.length() + &quot; bytes long.&quot;); System.out.println(fileName + &quot; is &quot; + fn.lastModified() + &quot; bytes long.&quot;); if (!fn.canWrite()) { System.out.println(fileName + &quot; is not writable.&quot;); } } }
  • 18. The Reader Class: Methods
  • 19. The Reader Class: Methods
  • 20. Node Reader Classes
  • 21. Filter Reader Classes
  • 22. The Writer Class: Methods
  • 23. Node Writer Classes
  • 24. Filter Writer Classes
  • 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...
  • 26. Basic Reader / Writer Example while ((data = reader.read() ) != -1) { writer.write(data); } reader.close(); writer.close(); } catch (IOException ie) { ie.printStackTrace(); } } //continued...
  • 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); } }
  • 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...
  • 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...
  • 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); } }
  • 31. The InputStream Class: Methods
  • 32. The InputStream Class: Methods
  • 33. Node InputStream Classes
  • 35. The OutputStream Class: Methods
  • 36. Node OutputStream Classes
  • 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...
  • 39. Basic InputStream / OutputStream Example while ((data = inputStr.read() ) != -1) { outputStr.write(data); } inputStr.close(); outputStr.close(); } catch (IOException ie) { ie.printStackTrace(); } } //continued...
  • 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); } }
  • 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...
  • 42. Modified InputStream / OutputStream Example while ((data = inputStr.read() ) != -1) { outputStr.println(&quot;read data: &quot; + (char) data); inputStr.unread(data); data = inputStr.read(); outputStr.println(&quot;unread data: &quot; + (char) data); } inputStr.close(); outputStr.close(); //continued...
  • 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); } }
  • 44. Serialization Definition: Supported by the Java Virtual Machine (JVM) Ability to read or write an object to a stream Process of &quot;flattening&quot; 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
  • 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
  • 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
  • 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
  • 48. Serialization: Writing an Object Stream Use the ObjectOutputStream class Use its writeObject method public final void writeObject(Object obj) throws IOException where, obj is the object to be written to the stream
  • 49. Serialization: Writing an Object Stream import java.io.*; public class SerializeBoolean { SerializeBoolean() { Boolean booleanData = new Boolean(&quot;true&quot;); try { FileOutputStream fos = new FileOutputStream(&quot;boolean.ser&quot;); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(booleanData); oos.close(); //continued...
  • 50. Serialization: Writing an Object Stream } catch (IOException ie) { ie.printStackTrace(); } } public static void main(String args[]) { SerializeBoolean sb = new SerializeBoolean(); } }
  • 51. Deserialization: Reading an Object Stream Use the ObjectInputStream class Use its readObject method public 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
  • 52. Deserialization: Reading an Object Stream import java.io.*; public class UnserializeBoolean { UnserializeBoolean() { Boolean booleanData = null; try { FileInputStream fis = new FileInputStream(&quot;boolean.ser&quot;); ObjectInputStream ois = new ObjectInputStream(fis); booleanData = (Boolean) ois.readObject(); ois.close(); //continued...
  • 53. Deserialization: Reading an Object Stream } catch (Exception e) { e.printStackTrace(); } System.out.println(&quot;Unserialized Boolean from &quot; + &quot;boolean.ser&quot;); System.out.println(&quot;Boolean data: &quot; + booleanData ); System.out.println(&quot;Compare data with true: &quot; + booleanData.equals(new Boolean(&quot;true&quot;)) ); } //continued...
  • 54. Deserialization: Reading an Object Stream public static void main(String args[]) { UnserializeBoolean usb = new UnserializeBoolean(); } }
  • 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
  • 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
  • 57. Summary Writer Classes Methods write , close , flush Node Writer Classes FileWriter , CharArrayWriter , StringWriter , PipedWriter Filter Writer Classes BufferedWriter , FilterWriter , OutputStreamWriter , PrintWriter
  • 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
  • 59. Summary OutputStream Classes Methods write , close , flush Node OutputStream Classes FileOutputStream , BufferedArrayOutputStream , PipedOutputStream Filter OutputStream Classes BufferedOutputStream , FilterOutputStream , ObjectOutputStream , DataOutputStream , PrintStream
  • 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