OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS

Slides:



Advertisements
Similar presentations
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.
Advertisements

Lecture 12 Recursion part 1
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 
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS 1 Copyright: FALL 2014 Illinois Institute of Technology_ George Koutsogiannakis.
Lecture 31 File I/O -Part 2 COMP1681 / SE15 Introduction to Programming.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
©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.
Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Exceptions and Input/Output Operations
Files and Streams (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
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.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Java I/O Writing and Reading Objects to File Serialization.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 Lecture 6 George Koutsogiannakis /Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
Object Persistence and Object serialization CSNB534 Asma Shakil.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
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.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
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.
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.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
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
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Streams. RHS – SWC 2 Binary files A binary file contains ”raw” bytes that can be interpreted as almost anything Can have any extension Can be created.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Object Writing in files
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
Memento Design Pattern
I/O Basics.
Chapter 17 Binary I/O 1.
Accessing Files in Java
Java Serialization B.Ramamurthy 11/8/2018 B.Ramamurthy.
Programming in Java Files and I/O Streams
Streams and File I/O Chapter 9 Chapter 9.
CS 116 Object Oriented Programming II
Java Serialization B.Ramamurthy 11/14/2018 B.Ramamurthy.
Working with files.
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Serialization and Deserialization Bullet points from Head First Java, Ch Dec-18 serialization.ppt.
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_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 I LECTURE 9 GEORGE KOUTSOGIANNAKIS
Podcast Ch23f Title: Serialization
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
TCSS 143, Autumn 2004 Lecture Notes
The command invocation protocol
David Davenport Spring 2005
Presentation transcript:

OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS CS 201 OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/ George Koutsogiannakis

Last Week’s Topics The java.io Package Reading Text Files Reading Structured Text Files Using StringTokenizer Reading using Streams Writing to Structured Text Files

New Topics Writing objects into a File. Reading objects from a File. Simple Recursion Recursion with a Return Value

Serialization Writing objects into a file involves a protocol of Java called: Serialization Objects are converted (serialized) into a byte stream and stored in the file. Reading objects from a file involves a protocol called deserialization. Objects are converted back to the particular data type that they belong to.

Serialization A State of an object is the particular value sof its attributes (fields) at a particular time. Saving a particular state via serialization is called “persistence”.

Writing Objects to a File To write an object to a file, its class must implement the Serializable interface, which indicates that: the object can be converted to a byte stream to be written to a file that byte stream can be converted back into a copy of the object when read from the file The Serializable interface has no methods to implement. All we need to do is: import the java.io.Serializable interface add implements Serializable to the class header i.e public class MyClass implements Serializable

The ObjectOutputStream Class The ObjectOutputStream class, coupled with the FileOutputStream class, provides the functionality to write objects to a file. The ObjectOutputStream class provides a convenient way to write objects to a file. Its writeObject method takes one argument: the object to be written.

Constructors for Writing Objects Class Constructor FileOutputStream FileOutputStream( String filename, boolean mode ) creates a FileOutputStream object from a String representing the name of a file. If the file does not exist, it is created. If mode is false, the current contents of the file, if any, will be replaced. If mode is true, writing will append data to the end of the file. Throws a FileNotFoundException. ObjectOutputStream ObjectOutputStream( OutputStream out ) creates an ObjectOutputStream that writes to the OutputStream out. Throws an IOException.

The writeObject Method See Examples 11.16 FlightRecord2.java and Example 11.17 WritingObjects.java Return value Method name and argument list void writeObject( Object o ) writes the object argument to a file. That object must be an instance of a class that implements the Serializable interface. Otherwise, a run-time exception will be generated. Throws an IOException.

Omitting Data from the File The writeObject method does not write any object fields declared to be static or transient. You can declare a field as transient if you can easily reproduce its value or if its value is 0. Syntax to declare a field as transient: accessModifier transient dataType fieldName Example: private transient double totalRevenue;

Reading Objects from a File The ObjectInputStream class, coupled with FileInputStream, provides the functionality to read objects from a file. The readObject method of the ObjectInputStream class is designed to read objects from a file. Because the readObject method returns a generic Object, we must type cast the returned object to the appropriate class. When the end of the file is reached, the readObject method throws an EOFException, so we detect the end of the file when we catch that exception.

Constructors for Reading Objects Class Constructor FileInputStream FileInputStream( String filename ) constructs a FileInputStream object from a String representing the name of a file. Throws a FileNotFoundException. ObjectInputStream ObjectInputStream( InputStream in ) creates an ObjectInputStream from the InputStream in. Throws an IOException.

The readObject Method See Example 11.18 ReadingObjects.java Note: Return value Method name and argument list Object readObject( ) reads the next object and returns it. The object must be an instance of a class that implements the Serializable interface. When the end of the file is reached, an EOFException is thrown. Also throws an IOException and ClassNotFoundException See Example 11.18 ReadingObjects.java Note: we detect reaching the end of the file in the EOFException catch block we use a finally block to close the file

Example Of Writing Objects We could serialize the VehicleA class by making a minor change to the class: public class VehicleA implements Serializable We can exclude certain fields of the class from being serialized (and thus have their values written) by using the keyword transient in front of the declaration of the field. i.e. private transient double init_v; private transient double init_d;

Example Of Writing Objects Now in a VehicleClient class we can save the state of a particular VehicleA object by writing it into a file. The file name usually has the extension .ser i.e. MyFile.ser Thus:

Example Of Writing Objects VehicleA va=new VehicleA(“My Vehicle”, 2, 3, 2.1, 3.5); try{ FileOutputStream fos=new FileOutputStream(“MyFile.ser”); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(va); oos.close(); } catch(IOException ioe) { System.out.println(“Error writing into file”); ioe.printStackTrace();

Example of Reading the Object From the File try{ FileInputStream fis = new FileInputStream(“MyFile.ser”); ObjectInputStream ois = new ObjectInputStream(fis); VehicleA vh = (VehicleA)ois.readObject(); ois.close(); } Catch(IOException ioe) { System.out.println(“Error writing into file”); ioe.printStackTrace(); We can output the object’s attributes and observe that the values are the same as the ones we wrote in the file.

Simple Recursion Sometimes large problems can be solved by transforming the large problem into smaller and smaller problems until you reach an easily solved problem. This methodology of successive reduction of problems is called Recursion. That easy-to-solve problem is called the base case. The formula that reduces the size of a problem is called the general case.

Recursive Methods A recursive method calls itself, i.e. in the body of the method, there is a call to the method itself. The arguments passed to the recursive call are smaller in value than the original arguments.

Simple Recursion When designing a recursive solution for a problem, we need to do the following: define the base case define the rule for the general case

Printing “Hello World” n Times Using Recursion In order to print “Hello World” n times (n is greater than 0), we can do the following: Print “Hello World” Print “Hello World” (n – 1) times This is the general case. We have reduced the size of the problem from size n to size (n – 1).

Printing “Hello World” n Times Using Recursion Printing “Hello World” (n – 1) times will be done by: Printing “Hello World” Printing “Hello World” (n – 2) times … and so on Eventually, we will arrive at printing “Hello World” 0 times: that is easy to solve; we do nothing. That is the base case.

Pseudocode for Printing “Hello World” n Times Using Recursion printHelloWorldNTimes( int n ) { if ( n is greater than 0 ) print “Hello World” printHelloWorldNTimes( n – 1 ) } // else do nothing

Coding the Recursive Method public static void printHelloWorldNTimes( int n ) { if ( n > 0 ) System.out.println( “Hello World” ); printHelloWorldNTimes( n – 1 ); } // if n is 0 or less, do nothing See Example 13.1 RecursiveHelloWorld.java

Recursion with a Return Value In a value-returning method, the return statement can include a call to another value-returning method. For example, public int multiplyAbsoluteValueBy3( int n ) { return ( 3 * Math.abs( n ) ); }

Recursion with a Return Value In a recursive value-returning method, the return statement can include a call to the method itself. The return value of a recursive value-returning method often consists of an expression that includes a call to the method itself: return ( expression including a recursive call to the method );

Calculating a Factorial The factorial of a positive number is defined as factorial( n ) = n! = n * ( n – 1 ) * ( n – 2 ) * … 3 * 2 * 1 By convention, factorial( 0 ) = 0! = 1 (The factorial of a negative number is not defined.) Can we find a relationship between the problem at hand and a smaller, similar problem?

Calculating a Factorial factorial( n ) = n * factorial( n – 1 ) At each step, the size of the problem is reduced by 1: we progress from a problem of size n to a problem of size (n – 1) A call to factorial( n ) will generate a call to factorial( n – 1 ), which in turn will generate a call to factorial( n – 2 ), …. Eventually, a call to factorial( 0 ) will be generated; this is our easy-to-solve problem. We know that factorial( 0 ) = 1. That is the base case.

Code for a Recursive Factorial Method public static int factorial( int n ) { if ( n <= 0 ) // base case return 1; else // general case return ( n * factorial( n – 1 ) ); } See Example 13.2 RecursiveFactorial.java

Common Error Trap In coding a recursive method, failure to code the base case will result in a run-time error. If the base case is not coded, when the method is called, the recursive calls keep being made because the base case is never reached. This eventually generates a StackOverflowError.

Study Guide Chapter 11 Chapter 13 Section 11.7, 11.8