Previous to Chapter 7 Files

Similar documents
Lecture 7. File Processing

CS112 Lecture: Streams

Java Programming Lecture 9

Chapter 17 Binary I/O. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

CPS122 Lecture: Input-Output

CPS122 Lecture: Input-Output

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

Exceptions Binary files Sequential/Random access Serializing objects

File IO. Binary Files. Reading and Writing Binary Files. Writing Objects to files. Reading Objects from files. Unit 20 1

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS 251 Intermediate Programming Java I/O Streams

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

FILE I/O IN JAVA. Prof. Chris Jermaine

Data Structures. Miscellaneous. Tentahjälpmedel Tentamen TDA550 1 (14) Tentahjälpmedel Tentamen TDA550 2 (14)

Java Object Serialization Specification

输 入输出相关类图. DataInput. DataOutput. java.lang.object. FileInputStream. FilterInputStream. FilterInputStream. FileOutputStream

Many Stream Classes. File I/O - Chapter 10. Writing Text Files. Text Files vs Binary Files. Reading Text Files. EOF with hasmoreelements()

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

What is Serialization?

I/O Streams. Object-oriented programming

CN208 Introduction to Computer Programming

Advanced Programming Methods. Seminar 12

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

Streams and File I/O

12% of course grade. CSCI 201L Final - Written Fall /7

Data Structures. 03 Streams & File I/O

Streams and File I/O

JAVABEANS CLASS TO BE A COMPONENT WHAT MAKES A DETAILED VIEW. Tomas Cerny, Software Engineering, FEE, CTU in Prague,

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output

COMP1406 Tutorial 11

Title Description Participants Textbook

Data stored in variables and arrays is temporary

Chapter 12. File Input and Output. CS180-Recitation

CS371m - Mobile Computing. Persistence

LARA TECHNOLOGIES EXAM_SPECIALSIX SECTION-1

Job Migration. Job Migration

Binary I/O. CSE 114, Computer Science 1 Stony Brook University

Basic Java IO Decorator pattern Advanced Java IO. Java IO - part 2 BIU OOP. BIU OOP Java IO - part 2

14.3 Handling files as binary files

Chapter 8: Files and Security

Assignment -3 Source Code. Student.java

File. Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

CMPSCI 187: Programming With Data Structures. Lecture #24: Files and a Case Study David Mix Barrington 2 November 2012

Chapter 10 Input Output Streams

Decorator Pattern. Decorator Pattern. Decorator Problems Decorator Examples Proxy Pattern. Motivation Structure Decorator vs Inheritance vs Strategy

STREAMS. (fluxos) Objetivos

Performing input and output operations using a Byte Stream

Saving and Loading Information

CSE 331. Memento Pattern and Serialization

Persistence. An Introduction to XML and Serialization. Dr. Siobhán Drohan Maireád Meagher. Produced by:

CPIT 305 Advanced Programming

CSD Univ. of Crete Fall Files, Streams, Filters

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Ch 7 Designing Java Classes & Class structure

Exceptions and Working with Files

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Chapter 11: Exceptions and Advanced File I/O

Ch 7 Designing Java Classes & Class structure. Fields have data values define/describe an instance

Software 1 with Java. Recitation No. 7 (Java IO) May 29,

Chapter 12: Exceptions and Advanced File I/O

Software 1 with Java. Recitation No. 9 (Java IO) December 10,

Software 1. Java I/O

CS108, Stanford Handout #33. Sockets

Example: Copying the contents of a file

Ch 7 Designing Java Classes & Class structure. Methods: constructors, getters, setters, other e.g. getfirstname(), setfirstname(), equals()

1.00 Lecture 30. Sending information to a Java program

Algorithms. Produced by. Eamonn de Leastar

CS1083 Week 2: Arrays, ArrayList

core Java Input/Output

Example: Tax year 2000

Java Input/Output Streams

Text User Interfaces. Keyboard IO plus

Optional Lecture Chapter 17 Binary IO

Name:... ID:... class A { public A() { System.out.println( "The default constructor of A is invoked"); } }

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

INFO1113. Calum Baird. October 5, Stuff Always check null Inline declare array Switch statement...

Intro to Computer Science II

Announcement EXAM 2. Assignment 6 due Wednesday WEDNESDAY 7: :00 PM EE 129

Darshan Institute of Engineering & Technology for Diploma Studies

School of Informatics, University of Edinburgh

When working with files and directories, it is often

Certification In Java Language Course Course Content

Active Learning: Streams

Oracle 1z Java Standard Edition 5 Programmer Certified Professional Upgrade Exam. Practice Test. Version:

About the Tutorial. Audience. Prerequisites. Disclaimer & Copyright. Avro

Serialisa(on, Callbacks, Remote Object Ac(va(on. CS3524 Distributed Systems Lecture 03

Chapter 12. File Input and Output. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

THIS EXAMINATION PAPER MUST NOT BE REMOVED FROM THE EXAMINATION ROOM

Hashing. Reading: L&C 17.1, 17.3 Eck Programming Course CL I

CS 180 Final Exam Review 12/(11, 12)/08

Files and IO, Streams. JAVA Standard Edition

Java Programming Unit 9. Serializa3on. Basic Networking.

Class Hierarchy II. Discussion E

Objec&ves. Review. Standard Error Streams

Fundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!

Programmierpraktikum

Files and Streams

Software 1. תרגול 9 Java I/O

Transcription:

Previous to Chapter 7 Files Recall Scanner from Part I notes. A scanner object can reference a text file Scanner f = new Scanner(new File("file name goes here")); Scanner methods can be applied to reading the file f.next() f.nextint() f.hasnext() Etc. 1

Previous to Chapter 7 Files Recall System.out from Part 1 notes. We can redirect output to a file File f = new File("myfile.txt"); FileOutputStream fs =new FileOutputStream(f); PrintStream ps = new PrintStream(fs); System.setOut(ps); System.out.println("your data goes here"); Redirecting output to a file instead of standard output 2

Ch 7 Files - Binary vs XML files Binary files Machine-readable Efficient for space and time Data stored on disk just as stored in memory Extensible Markup Language (XML) files Human-readable Stored in text format with XML tags Easily viewed using a browser or word processor 3

Ch 7 Files storing values vs objects First we consider storing and retrieving values in files Primitive values: int, double, boolean, Strings Then we consider storing and retrieving objects a whole object graph is unit of transfer 4

Storing values (primitive data & strings) in files First we consider Binary files Then we consider XML files Binary files: listings 7.1, 7.2 using a file named mydata.ser XML files: listings 7.3, 7.4 using a file named mydata.xml Examples write/read an int array of 5 values: 5 20 30 2 7 5

Binary files: primitive data & strings We will use Java classes DataOutputStream and DataInputStream Methods of DataOutputStream close() writeboolean(boolean b) writebyte(byte b) writechar(int c) writedouble(double d) writefloat(float f) writeint(int i) writelong(long m) writeshort(short s) writeutf(string s) Methods of DataInputStream close() readboolean() readbyte() readchar() readdouble() readfloat() readint() readlong() readshort() readutf() Choose method for the data type for strings 6

Writing primitive data & strings to binary file, Listing 7.1 File to create import java.io.dataoutputstream; import java.io.fileoutputstream; Errors could occur: import java.io.ioexception; file not found, out of space, public class WriteBinary { public static void main(string[] args) throws IOException { 5 values to write int[] mydata = {5, 20, 30, 2, 7; DataOutputStream os = new DataOutputStream( new FileOutputStream("myData.ser")); for (int i=0; i<5; i++) os.writeint(mydata[i]); os.close(); Close the file Write values Note: the file mydata.ser is stored in a binary form and so it is not human-readable; it is machine-readable. 7

Reading primitive data & strings from binary file, Listing 7.2 File to read import java.io.datainputstream; import java.io.fileinputstream; import java.io.ioexception; public class ReadBinary { public static void main(string[] args) throws IOException { int[] mydata = new int[5]; DataInputStream is = new DataInputStream( new FileInputStream("myData.ser")); // get values from file into array for (int i=0; i<5; i++) mydata[i] = is.readint(); // display values in array Errors could occur: file not found, data missing, for (int i: mydata)system.out.println(i); is.close(); Close the file Get values 8

XML files XML files are text files human readable Values are enclosed in XML tags, for example <int>183</int> For output use class XMLEncoder and method writeobject For input use class XMLDecoder and method readobject 9

Writing primitive data & strings to XML, Listing 7.3 import java.beans.xmlencoder; import java.io.fileoutputstream; import java.io.ioexception; public class WritePrimitiveDataToXML { public static void main(string[] args) throws IOException{ XMLEncoder encoder = new XMLEncoder(new FileOutputStream("myData.xml")); int[] mydata = {5, 20, 30, 2, 7; for (int i=0; i<5; i++) encoder.writeobject(mydata[i]); encoder.close(); Close the file Write values Note: the file xml is stored in a XML form and is human-readable Errors could occur: file not found, out of space, File to create 5 values to write 10

XML files contents of mydata.xml Extensible Markup Language (XML) files are human-readable where data is encoded in XML tags The 5 values 5, 20, 30, 2, 7 are written to mydata.xml which is: Java data occurs between <?xml version="1.0" encoding="utf-8"?> <java version="1.8.0_60" class="java.beans.xmldecoder"> <int>5</int> <int>20</int> <int>30</int> <int>2</int> <int>7</int> </java> Five integers each enclosed in XML tags <int> and </int> Try opening the file mydata.xml in a browser or word editor 11

Reading primitive data & strings from XML, Listing 7.4 import java.beans.xmldecoder; import java.io.fileinputstream; import java.io.ioexception; public class ReadPrimitiveDataFromXML { public static void main(string[] args) throws IOException{ // decoder object references the XML file XMLDecoder decoder = new XMLDecoder(new FileInputStream("myData.xml")); // get the five int values int[] mydata = new int[5]; for (int i=0; i<5; i++) mydata[i] = (int) decoder.readobject(); // display the array and close the file for (int i: mydata) System.out.println(i); decoder.close(); Close the file Errors could occur: file not found, data missing, File to read Get values Read as an object need to cast to int 12

Summary - primitive values & strings Programming for binary files is very similar to the programming required for XML files. XML files are human-readable. Processing binary files will always be more efficient virtually no translation of information required. 13

Objects Now we examine writing/reading whole objects to/from a file 1. Binary files 2. XML files Writing objects out to a file is referred to as serializing objects Rather than one object, an object graph is read/written An object graph consists of an object and all objects reachable from that object. 14

Objects Our examples will use the object graph below which consists of an array list and its elements Four objects Binary files: listings 7.5, 7.6 examples use a file named practitioners.ser XML files: listings 7.7, 7.8 examples use a file named practitioners.xml 15

Objects and binary files The objects must be instantiated from a class that implements Serializable Recall Listing 5.2 that defines the Practitioner class: Add this line import java.io.serializable; public class Practitioner implements Serializable{ private String firstname; private String lastname; Add implements Serializable private String gender; public Practitioner() { firstname = lastname = gender = "unknown"; Now we can write Practitioner objects to a binary file 16

Binary files: writing objects Binary files are machine-readable, efficient use of storage and time We will use class ObjectOutputStream To write an object graph use writeobject( ) Class must implement Serializable Example writes to a file named practitioners.ser 17

Writing Objects to a binary file, Listing 7.5 import java.io.objectoutputstream; import java.io.fileoutputstream; import java.io.ioexception; import java.util.arraylist; public class PractitionersToBinary { public static void main(string[] args) throws IOException { // List of practitioners ArrayList<Practitioner> practitioners = new ArrayList(); // Create some practitioners Practitioner pr = new Practitioner("Sam","Smith","female"); Doctor dr = new Doctor("Jill","Jones","female","Dermatology"); Pharmacist ph = new Pharmacist("Eddy","Edwards","male","Drugco"); practitioners.add(pr); practitioners.add(dr); practitioners.add(ph); // create an object to reference practitioners.ser ObjectOutputStream os = new ObjectOutputStream ( new FileOutputStream("practitioners.ser")); os.writeobject (practitioners); os.close(); Needed to write objects An ArrayList and its contents The file to create One writeobject for the ArrayList object 18

Binary files: reading objects We will use Java class ObjectInputStream To read an object graph we use readobject() Example reads from the file practitioners.ser 19

Reading Objects from a binary file, Listing 7.6 import java.io.objectinputstream; Needed to read import java.io.fileinputstream; objects import java.io.ioexception; import java.util.arraylist; public class PractitionersFromBinary { public static void main(string[] args) throws IOException, ClassNotFoundException{ ObjectInputStream is = new ObjectInputStream( new FileInputStream("practitioners.ser")); // The JVM only knows the object read as being of type Object. // Since we know the object being read is of type ArrayList // we include a cast to type ArrayList to the right of // the assignment operator. ArrayList<Practitioner> practitioners = (ArrayList) is.readobject(); is.close(); for (Practitioner p: practitioners) { String type="practitioner"; if (p instanceof Doctor) type="doctor"; if (p instanceof Pharmacist) type="pharmacist"; System.out.println(type+" "+p.getfirstname()); The file to read Get the whole ArrayList object in one read Iterate through the array list and display each practitioner. 20

Objects and XML files Use XMLEncoder and XMLDecoder Class must have A no-arg constructor Getters Setters Different from binary files Use writeobject( ) and readobject() Write, read whole object graph at a time. 21

XML files: writing objects XML files are human-readable Verbose - XML tags identify the type of element We will use Java class XMLEncoder To write an object graph use writeobject( ) Class must have no-arg constructor, getters, setters Example writes to a file named practitioners.xml 22

Writing Objects to XML file, Listing 7.7 import java.beans.xmlencoder; import java.io.fileoutputstream; import java.io.ioexception; import java.util.arraylist; public class PractitionersToXML { public static void main(string[] args) throws IOException{ // List of practitioners ArrayList<Practitioner> practitioners = new ArrayList(); // Create some practitioners Practitioner pr = new Practitioner("Sam","Smith","female"); Doctor dr = new Doctor("Jill","Jones","female","Dermatology"); Pharmacist ph = new Pharmacist("Eddy","Edwards","male","Drugco"); practitioners.add(pr); practitioners.add(dr); practitioners.add(ph); // the encoder object references the file XMLEncoder encoder = new XMLEncoder( new FileOutputStream("practitioners.xml")); // write out the practitioner object graph encoder.writeobject(practitioners); // close the xml file encoder.close(); Needed to write objects The file to create An ArrayList and its contents One writeobject for the ArrayList object 23

XML files: reading objects We will use Java class XMLDecoder To read an object graph we use readobject() Example reads a file named practitioners.xml Note the XML file is self-describing, contents next slide 24

XML files: reading objects contents of practitioners.xml <?xml version="1.0" encoding="utf-8"?> <java version="1.8.0_60" class="java.beans.xmldecoder"> <object class="java.util.arraylist"> <void method="add"> <object class="practitioner"> <void property="firstname"> <string>sam</string> </void> <void property="gender >... First object to recreate Second object to recreate First field is firstname with value Sam 25

Reading Objects from XML, Listing 7.8 import java.beans.xmldecoder; import java.io.fileinputstream; import java.io.ioexception; import java.util.arraylist; public class PractitionersFromXML { public static void main(string[] args) throws IOException{ // decoder object references the xml file XMLDecoder decoder = new XMLDecoder( new FileInputStream("practitioners.xml")); // The JVM only knows the object read as being of type Object. // Since we know the object being read is of type ArrayList // we include a cast to type ArrayList to the right of // the assignment operator. ArrayList<Practitioner> practitioners = (ArrayList) decoder.readobject(); decoder.close(); // display the practitioners, doctors, etc. for (Practitioner p: practitioners) { String type="practitioner"; if (p instanceof Doctor) type="doctor"; if (p instanceof Pharmacist) type="pharmacist"; System.out.println(type+" "+p.getfirstname()); Needed to read objects The file to read Get the whole ArrayList object in one read Iterate through the array list and display each practitioner. 26

Summary - Serializing Objects Being able to serialize objects is important as it provides the information that enables objects to be re-instantiated at a later time by another program. Objects do not have to be destroyed when a program ends. Serialization provides a form of persistence similar to that provided in database systems, but not with all the features that make databases unique. Programming serialization of objects with binary files is very similar to the programming required for XML files. XML files are a human-readable. Processing binary files will always be more efficient virtually no translation of information required. 27

Summary - Serializing Objects Serializing objects Object graphs Casting Binary files Serializable interface XML files No-arg constructors Getters Setters 28