Java I/O Writing and Reading Objects to File Serialization.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Advertisements

The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Serialization Flatten your object for automated storage or network.
Slide 10.1 Advanced Programming 2004, based on LY Stefanus’s Slides Object Serialization Object serialization: the process of converting an object into.
Chapter - 12 File and Streams (continued) This chapter includes -  DataOutputStream  DataInputStream  Object Serialization  Serializing Objects 
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
1 Chapter 8 Three Interfaces: Cloneable, Serializable, and Runnable.
Simple Java I/O Part I General Principles. 2 Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
Unit 211 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files.
Unit 201 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Serializable Objects Serializable objects –Directly read/write from/to disk with a single statement –Convert from/to a sequence of bytes when read/write.
Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
13-Jul-15 Simple Java I/O Part I General Principles.
15-Jul-15 Simple Java I/O Part I General Principles.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Exceptions and Input/Output Operations
Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with.
A Few Exceptions, A Little IO, and Persistent Objects Rick Mercer.
Files and Streams (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
Working with files By the end of this lecture you should be able to: explain the principles of input and output and identify a number of different input.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
 Pearson Education, Inc. All rights reserved Files and Streams.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
Serialization CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 11 Exceptions and Input/Output Operations.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
Files and Serialization. Files Used to transfer data to and from secondary storage.
File Input & Output1 Streams & File I/O. Introduction (1) The Java platform includes a number of packages that are concerned with the movement of data.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
CS 116 Object Oriented Programming II Lecture 11 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Object Writing in files
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
I/O Basics.
Accessing Files in Java
Java Serialization B.Ramamurthy 11/8/2018 B.Ramamurthy.
Client server programming
CS 116 Object Oriented Programming II
Java Serialization B.Ramamurthy 11/14/2018 B.Ramamurthy.
Serialization and Deserialization Bullet points from Head First Java, Ch Dec-18 serialization.ppt.
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Podcast Ch23f Title: Serialization
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
The command invocation protocol
Presentation transcript:

Java I/O Writing and Reading Objects to File Serialization

2 Storing Objects/Structures in Files Many programs need to save information between program runs Alternately, we may want one program to save information for later use by another program

3 Serialization of Objects Java provides a way to save objects directly Saving an object with this approach is called serializing the object Serialization in other languages can be very difficult, because objects may contain references to other objects. Java makes serialization (almost) easy Any object that you plan to serialize must implement the Serializable interface

4 Conditions for serializability If an object is to be serialized: The class must be declared as public The class must implement Serializable If the object is a sub type of another class, the parent class must have a no-argument constructor All fields of the class must be serializable: either primitive types or serializable objects

5 Implementing Serializable To “implement” an interface means to define all the methods declared by that interface, but... The Serializable interface does not define any methods! Question: What possible use is there for an interface that does not declare any methods? Answer: Serializable is used as flag to tell Java it needs to do extra work with this class When an object implements Serializable, its state is converted to a byte stream to be written to a file so that the byte stream can be converted back into a copy of the object when it is read from the file.

6 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 except that the class must implement Serializable. You must also import java io which contains all the streams needed.

7 The Object Streams  You need to use the ObjectOutputStream class for storing objects and the ObjectInputStream class for restoring objects.  These two classes are built upon several other classes.  The basic code is as follows:

8 Writing objects to a file ObjectOutputStream objectOut = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(fileName))); objectOut.writeObject(serializableObject); objectOut.close( );

9 A Serializable Version of a Circle Class

10 A Program to Save a SCircle Object

11 public class FlightRecord implements Serializable { public static final DecimalFormat MONEY = new DecimalFormat( "$###.00" ); private String flightNumber; // ex. = AA123 private String origin; // origin airport; ex. = BWI private String destination; // destination airport; ex. = O’Hare private int numPassengers; // number of passengers private double avgTicketPrice; // average ticket price // Constructor public FlightRecord( String startFlightNumber, String startOrigin, String startDestination, int startNumPassengers, double startAvgTicketPrice ) { flightNumber = startFlightNumber; origin = startOrigin; destination = startDestination; numPassengers = startNumPassengers; avgTicketPrice = startAvgTicketPrice; }

12 Flight Record class public String toString( ) { return "Flight " + flightNumber + ": from " + origin + " to " + destination + "\n\t" + numPassengers + " passengers" + "; average ticket price: " + MONEY.format( avgTicketPrice ); } // accessors, mutators, and other methods … }

13 import java.io; public class WritingObjects { public static void main( String [] args ) { // instantiate the objects FlightRecord2 fr1 = new FlightRecord2( "AA31", "BWI", "SFO",200, ); FlightRecord2 fr2 = new FlightRecord2( "CO25", "LAX", "JFK",225, ); FlightRecord2 fr3 = new FlightRecord2( "US57", "IAD", "DEN"175, ); try { FileOutputStream fos = new FileOutputStream( "objects" ); ObjectOutputStream oos = new ObjectOutputStream( fos ); // write the objects to the file oos.writeObject( fr1 ); oos.writeObject( fr2 ); oos.writeObject( fr3 ); // release resources associated with the objects file oos.close( ); }

14 catch( FileNotFoundException e ) { System.out.println( "Unable to write to objects" ); } catch( IOException e ) { ioe.printStackTrace( ); } } }

15 Saving Hierarchical Objects Ensure that each of the objects involved implements the Serializable interface import java.io*; public class SPoint implements Serializable { public int xValue; // this is for example only public int yValue; } import java.io*; public class SNewCircle implements Serializable { public SPoint location; public float radius; public boolean soldi; } // initialize location’s xValue and yValue

16 Reading Objects from a file ObjectInputStream reads objects from a file. The readObject() method reads the next object from the file and returns it. Because it returns a generic object, the returned object must be cast to the appropriate class. When the end of file is reached, it throws an EOFException versus when reading from a text file where a null String is returned.

17 Reading objects from a file ObjectInputStream objectIn = new ObjectInputStream( new BufferedInputStream( new FileInputStream(fileName))); myObject = (itsType) in.readObject( ); // some code objectIn.close( );

18 import java.io.; public class GetCircle { public static void main( String [] args ) { SCircle s2 = new SCircle(); ObjectInputStream in =new ObjectInputStream( new BufferedInputStream(new FileInputStream(Objects.dat))); try { s2 = (SCircle) in.readObject(); } catch (Exception e) { System.out.println (“ Error in reading “ + e) } System.out.println( “ The value of xvalue is “ + s2.xValue; System.out.println( “ The value of yvalue is “ + s2.yValue; } in.close(); }

19 import java.io.ObjectInputStream; public class ReadingObjects { public static void main( String [] args ) { try { FileInputStream fis = new FileInputStream( "objects " ); ObjectInputStream ois = new ObjectInputStream( fis ); try { while ( true ) { // read object, type cast returned object to FlightRecord FlightRecord2 temp = ( FlightRecord2 ) ois.readObject( ); // print the FlightRecord2 object read System.out.println( temp ); } } // end inner try block catch( EOFException eofe ) { System.out.println( "End of the file reached" ); }

20 catch( ClassNotFoundException e ) { System.out.println( cnfe.getMessage( ) ); } finally { System.out.println( "Closing file" ); ois.close( ); } } // end outer try block catch( FileNotFoundException e ) { System.out.println( "Unable to find objects" ); } catch( IOException ioe ) { ioe.printStackTrace( ); } } }

21 Reading Objects from a file. The while loop runs until the end of file is reached and an exception is thrown Control goes to the catch block and will always execute in a normal program run. The EOFException catch block must come before IOException as it is subclass of IOException. Otherwise the program will not produce the correct stack trace.

22 Output from reading objects ----jGRASP exec: java ReadingObjects Flight AA31: from BWI to SFO 200 passengers; average ticket price: $ Flight CO25: from LAX to JFK 225 passengers; average ticket price: $ Flight US57: from IAD to DEN 175 passengers; average ticket price: $ End of the file reached // EOF exception caught Closing file

23 Static members of a class A file containing objects can be quite large as not only does the objects data get written but: the name of the class, a description of each data field and other information needed to reconstruct the objects when the file is subsequently read. WriteObject() does not write static class members. Because we made MONEY – an object of DecimalFormat class – static in the FlightRecord class – the size of the object written was 241 bytes long. If MONEY were not static, it would be 2000 bytes approximately.

24 Transient instance variables Also, instance variables of type transient are not written to file. A variable can be designated transient if they can easily be reproduced or if their value is 0 at the time the file is created. For instance if we had a variable totalRevenue in the FlightRecord class which is calculated by multiplying totalPassengers times avgTicketPrice, we could declare totalRevenue transient as it can easily be recalculated. private transient double totalRevenue

25 Saving Structures Arrays- Assuming the array contains homogeneous data, this is easy Array-Based Lists- Save the array information as described above Reference-Based Lists- We cannot save and restore references as we save and restore primitive data

26 Saving Structures in Text Files (Cont’d) A Linked List as a Array of Nodes- This approach to implementing a linked list makes it easy to save the structure information in a file Binary Search Trees- A binary tree can also be implemented with an array of nodes. In that case, it is a simple matter to store and retrieve the tree Graphs- If the array- based approach is used we could safely save and reconstruct our graphs

27 Serialization is not trivial and should be used with care as it exposes the class to public use.