Files and Serialization. Files Used to transfer data to and from secondary storage.

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
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.
Java I/O The Cheat Sheet. Reading and Writing The basic architecture of Java IO is pluggable. The idea is to have some very simple classes do very simple.
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 
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
Lecture 31 File I/O -Part 2 COMP1681 / SE15 Introduction to Programming.
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
©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.
Lecture 7 File I/O (and a little bit about exceptions)‏
File-based Persistence: Serializability COMP53 Dec 7, 2007.
Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
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.
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
Java I/O Writing and Reading Objects to File Serialization.
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Working with files. RHS – SOC 2 Motivation All our programs so far have only worked with data stored in primary storage (RAM) Data is lost when program.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
© Amir Kirsh Files and Streams in Java Written by Amir Kirsh.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
 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.
Object Serialization. Sequential-access Text Files Sequential-access files store records In order by the record-key field Java imposes no structure on.
©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.
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.
CSI 3125, Preliminaries, page 1 Files. CSI 3125, Preliminaries, page 2 Reading and Writing Files Java provides a number of classes and methods that allow.
CSE 1020: Exceptions and A multiclass application Mark Shtern 1-1.
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.
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.
XSLT in Practice. Exercises  download Apache Xalan - install it - try the example in Xalan-Java Overview  ZVON XSLT Tutorial.
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
Lecture 8: I/O Streams types of I/O streams Chaining Streams
CSG2H3 Object Oriented Programming
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Memento Design Pattern
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.
Working with files.
Serialization and Deserialization Bullet points from Head First Java, Ch Dec-18 serialization.ppt.
Computer Science and Engineering
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
Java Basics Introduction to Streams.
The command invocation protocol
Presentation transcript:

Files and Serialization

Files Used to transfer data to and from secondary storage

A Portion of Java ’ s File Classes Object InputStreamOutputStream FileInputStreamFileOutputStreamObjectInputStreamObjectOutputStream File These classes are included in the java.io package, which must be imported into any application that uses them

Basic Algorithm for File Output Open an output connection to a file Write the data to the file Close the output connection to the file FileOutputStream Disk

Files and Exceptions Java requires the programmer to catch file exceptions For example, an IOException can be thrown during at attempt to open a file

try - catch Format try{ }catch( e){ }. catch( e){ } The exception thrown by try is matched against the parameter of each catch in sequence.

Writing Objects to Text Files Student s = new Student("Ken", 10); try{ FileOutputStream fos = new FileOutputStream("student.txt"); PrintWriter writer = new PrintWriter(fos); writer.println(s.getName()); writer.println(s.getNumScores()); for (int i = 1; i <= s.getNumScores(); i++) writer.println(s.getScore(i)); fos.flush(); fos.close(); }catch(Exception e){ System.out.println("Error in output:" + e.toString()); } Must agree with input process about format of text file.

Basic Algorithm for File Input Open an input connection to a file Read the data from the file and process it Close the input connection to the file FileInputStream Disk

Reading Objects from Text Files Student s = null; try{ FileInputStream fis = new FileInputStream("student.txt"); Scanner reader = new Scanner(fis); String name = reader.nextLine(); int numScores = Integer.parseInt(reader.nextLine()); s = new Student(name, numScores); for (i = 1; i <= numScores; i++) s.getScore(Integer.parseInt(reader.nextLine)); fis.close(); }catch(Exception e){ System.out.println("Error in output:" + e.toString()); } Must agree with output process about format of text file.

A Simpler Solution: Serialization A data model is said to be serialized when it can be permanently saved on a storage medium Serialization requires file management OOP systems support object serialization

Serializing a Data Model All classes to be serialized must implement the Serializable interface This interface is defined in the java.io package Many standard java classes are already serializable

import java.io.Serializable; public class Student implements Comparable, Serializable{. } Serializing the Student Class Many of Java ’ s data classes are already serializable All specialized data classes should be made to be serializable

Writing Objects to Object Files Create a new instance of FileOutputStream Wrap around this object a new instance of ObjectOutputStream Use the method writeObject to send an object out on the stream

Writing Objects to Output Files new FileOutputStream( ) new ObjectOutputStream( ).writeObject( ) A file name

Writing Objects to Output Files Student s = new Student("Ken", 10); try{ FileOutputStream fos = new FileOutputStream("student.dat"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(s); fos.flush(); fos.close(); }catch(Exception e){ System.out.println("Error in output:" + e.toString()); } Writes the whole Student object to the file without any fuss.

Reading Objects from Input Files Create a new instance of FileInputStream Wrap around this object a new instance of ObjectInputStream Use the method readObject to receive an object from the stream Cast the received object to its actual class

Reading Objects from Input Files new FileInputStream( ) new ObjectInputStream( ) ( ).readObject() A file name

Reading Objects from Input Files Student s; try{ FileInputStream fis = new FileInputStream("student.dat"); ObjectInputStream ois = new ObjectInputStream(fis); s = (Student) ois.readObject(); fis.close(); }catch(Exception e){ System.out.println("Error in input:" + e.toString()); } Reads the whole Student object from the file without any fuss.

Define a static Method for Input static public readFromFile(ObjectInputStream ois){ try{ return (Student) ois.readObject(); }catch(Exception e){ System.out.println("Error in input:" + e.toString()); return null; } try{ // Open file input stream and object input stream // while there are more objects to be read studentList.add(Student.readfromFile(ois)); } catch(Exception e){ … Alternatively, write and read the entire list!