Object Oriented Design with UML and Java. PART VIII: Java IO

Similar documents
CS 251 Intermediate Programming Java I/O Streams

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

Chapter 4 Java I/O. X i a n g Z h a n g j a v a c o s q q. c o m

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

Software 1. Java I/O

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

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

Java Input/Output Streams

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

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

Object-Oriented Programming in the Java language

CSE 331. Memento Pattern and Serialization

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

PIC 20A Streams and I/O

What is Serialization?

File Input/Output. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

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

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

CSB541 Network Programming 網路程式設計. Ch.2 Streams 吳俊興國立高雄大學資訊工程學系

CSC 1214: Object-Oriented Programming

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

Java Input / Output. CSE 413, Autumn 2002 Programming Languages.

The Java I/O System. Binary I/O streams (ASCII, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Lecture 11.1 I/O Streams

Simple Java Input/Output

Jonathan Aldrich Charlie Garrod

Byte and Character Streams. Reading and Writing Console input and output

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

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

I/O Streams. Object-oriented programming

Java Input/Output. 11 April 2013 OSU CSE 1

Exceptions and Working with Files

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

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

Software 1 with Java. The java.io package. Streams. Streams. Streams. InputStreams

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

Objec&ves STANDARD ERROR. Standard Error Streams. Ø Byte Streams Ø Text Streams 10/5/16. Oct 5, 2016 Sprenkle - CSCI209 1

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Chapter 10 Input Output Streams

Special error return Constructors do not have a return value What if method uses the full range of the return type?

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Object-Oriented Programming Design. Topic : Streams and Files

Data Structures. 03 Streams & File I/O

1.00 Lecture 30. Sending information to a Java program

Chapter 10. IO Streams

Streams and File I/O

Pieter van den Hombergh Richard van den Ham. March 13, 2018

Software 1. The java.io package. Streams. Streams. Streams. InputStreams

Example: Copying the contents of a file

Networking Code CSCI 201 Principles of Software Development

Techniques of Java Programming: Streams in Java

Files and Streams

Getting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park

CSE 143 Lecture 22. The Object class; Polymorphism. read slides created by Marty Stepp and Ethan Apter

ITI Introduction to Computer Science II

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

Principles of Software Construction: Objects, Design and Concurrency. Design Case Study: Stream I/O. toad

Chapter 12. File Input and Output. CS180-Recitation

Darshan Institute of Engineering & Technology for Diploma Studies

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax

Course Content. Objectives of Lecture 22 File Input/Output. Outline of Lecture 22. CMPUT 102: File Input/Output Dr. Osmar R.

Java Programming Lecture 9

The I/O Package. THE Java platform includes a number of packages that are concerned with the CHAPTER20

Streams and File I/O

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

PROGRAMACIÓN ORIENTADA A OBJETOS

CS11 Java. Fall Lecture 4

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

Job Migration. Job Migration

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Software Practice 1 - File I/O

CS112 Lecture: Streams

CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams

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

CS Programming I: File Input / Output

Certification In Java Language Course Course Content

CPS122 Lecture: Input-Output

Princeton University COS 333: Advanced Programming Techniques A Subset of Java

FILE I/O IN JAVA. Prof. Chris Jermaine

Java IO and C++ Streams

CN208 Introduction to Computer Programming

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

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

Advanced Object-Oriented Programming Streams and Files

I/O streams. Byte Streams Character Streams InputStream ByteArrayInputStream FileInputStream FilterInputStream

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

C17: I/O Streams and File I/O

CS Programming I: File Input / Output

Objec&ves. Review. Standard Error Streams

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B

Character Stream : It provides a convenient means for handling input and output of characters.

CPS122 Lecture: Input-Output

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

I/O STREAM (REQUIRED IN THE FINAL)

CS 200 File Input and Output Jim Williams, PhD

Transcription:

Object Oriented Design with UML and Java PART VIII: Java IO Copyright David Leberknight and Ron LeMaster. Version 2011

java.io.* & java.net.* Java provides numerous classes for input/output: java.io.inputstream & java.io.outputstream are abstract classes designed for reading and writing bytes. java.io.reader & java.io.writer are at the top of an analogous class hierarchy designed for reading and writing characters (16 bit unicode). java.io.file provides services for accessing native files and directories. java.nio.* New IO Check out the Apache MINA project, a framework built using java.nio to facilitate building high performance, high scalability network applications over TCP/IP and UDP. NIO.2 File System released with JDK 7 The java.net package has useful classes that work in harmony with java.io... java.net.url for locating Files. java.net.socket uses an InputStream and an OutputStream for distributed communications. ( VIII ) Java IO - 2

java.io.outputstream java.io.outputstream has numerous subclasses, including: ByteArrayOutputStream - Writes to a byte[] in memory. FileOutputStream - Writes to a File. FilterOutputStream - Decorates another OutputStream with filtering. ObjectOutputStream - Decorates another OutputStream with the ability to stream a serializable Object (to a File, byte[],, or another decorator). PipedOutputStream - Allows communication between Threads; one Thread writes to an OutputStream, while the other reads from an InputStream. PrintStream - Decorates another OutputStream, providing convenience methods for writing Java s primitive data types.... ( VIII ) Java IO - 3

java.io.printstream public class PrintStream extends FilterOutputStream { public PrintStream( OutputStream out ) public void close() public void flush() public void print( ) public void println( )... } System.out refers to an instance of class PrintStream. PrintStream translates your convenient print( ) method calls into the appropriate write( ) calls of its underlying OutputStream. Note: invoke flush() on an OutputStream whenever you want the output to be sent to the other end of the stream (byte[], File, Socket, etc.) as soon as possible (otherwise it might be buffered - held in memory). ( VIII ) Java IO - 4

Decorator Design Pattern out OutputStream << abstract >> + close() + flush() + write(... ) out FileOutputStream + FileOutputStream( File f ) + FileOutputStream( name : String, append : boolean ) ByteArrayOutputStream + tobytearray() : byte[] FilterOutputStream + FilterOutputStream( OutputStream out ) + write(... ) ObjectOutputStream + ObjectOutputStream( OutputStream out ) + writeobject( Object o ) PrintStream + print(... ) + println(... ) ( VIII ) Java IO - 5

Decorator Design Pattern (cont.) serializable : MyClass uses : ObjectOutputStream decorates : FileOutputStream In this example, an instance of MyClass (which implements the Serializable interface, discussed next) uses an ObjectOutputStream to serialize itself to a file. The ObjectOutputStream decorates the FileOutputStream, dynamically adding the new capability to be able to serialize an Object. ( VIII ) Java IO - 6

Decorator Design Pattern (cont.) Intent: Extend the responsibilities of an object without subclassing. Decorators may be chained together dynamically, so that each performs some new function and then delegates to the next object for further processing. ObjectOutputStream 'decorates' OutputStream, by providing a way to serialize an Object, which then can be further streamed into a File, a byte[], or across a network Socket to another machine, PrintStream 'decorates' OutputStream, by translating convenient calls to print( ) into the appropriate write( ) calls of its underlying OutputStream. Note the conspicuous lack of classes: ObjectFileOutputStream, ObjectByteArrayOutputStream, PrintFileOutputStream, ( VIII ) Java IO - 7

Java Serialization Supported directly by language in Java and Smalltalk. Supported through vendor-specific toolkits in C++. Pros: With language or toolkit support, it is simple and straightforward. Can be used for quick-and-dirty persistence on a project before the real database is up and running. Useful for things other than persistence, such as for passing Objects as parameters to distributed messaging. Cons: Startup or searching can be expensive if a large number of objects are stored. No transaction support. Not a substitute for a real database. ( VIII ) Java IO - 8

Serialization (cont.) Objects know how to write and read themselves as byte sequences. The language run-time knows how to deal with base-type attributes. Component objects are recursively serialized down to their base-type attributes, or the base class of the language. Issues: Because of its recursive nature, storing or loading one object may pull in many, many others. If a particular object is referenced by several others, we don t want multiple copies of the first object saved and restored. How might Graph Theory be used to work around this problem? Not all fields of an object should be serialized (transient). Versioning can be tricky. Since we are serializing objects, not classes, static fields do not get serialized; they remain unchanged, or they get initialized to null/0/false for the first instance of the class to be created. ( VIII ) Java IO - 9

Serialization (cont.) o0 : MyClass o1 : X o2 : X o3 : X o4 : X o5 : X When we serialize o0, we want to also serialize o1, o2, o3, o4, and o5 (the entire graph), but we only want one serialized copy of each instance. Java serialization takes care of this automatically. ( VIII ) Java IO - 10

Java Serialization Provided as a marker interface. No interface functions need to be implemented. public interface java.io.serializable {} Solves the multiple-instance Graph Theory problem. Can be customized. Attributes declared as transient are not serialized. The entire storage mechanism can be over-ridden.» readobject() & writeobject() ( VIII ) Java IO - 11

Java Serialization (cont.) // Write an object s non-transient state to a file... // For this to work, SerializationTest must implement Serializable SerializationTest st = new SerializationTest( 1, 2, 3 ); FileOutputStream fileout = new FileOutputStream( st.sav ); ObjectOutputStream output = new ObjectOutputStream( fileout ); output.writeobject( st ); output.flush(); output.close(); // Read the object s non-transient state from the file... FileInputStream filein = new FileInputStream( st.sav ); ObjectInputStream input = new ObjectInputStream( filein ); st = (SerializationTest) input.readobject(); input.close(); ( VIII ) Java IO - 12

Reading a file Use FileReader Decorate FileReader with BufferedReader to get readline() import java.io.*; FileReader fr = new FileReader( foo.txt ); BufferedReader br = new BufferedReader( fr ); String linefromfile = br.readline(); while( linefromfile!= null ) { System.out.println( New Line : + linefromfile ); linefromfile = br.readline(); } br.close(); ( VIII ) Java IO - 13

Example: StackTrace.toString() java.lang.throwable s printstacktrace() writes to System.out: java.lang.outofmemoryerror at fractal.fractalcalculator.getcolornumbers( FractalCalculator.java:147) at fractal.fractalcalculator.calcfractal(fractalcalculator.java:66) at fractal.fractalcalculator.run(fractalcalculator.java:184) at java.lang.thread.run(thread.java:474) How might we get this information into a String? If you look at Class Throwable s interface, you will see that printstacktrace() is overloaded, having a version that takes a PrintWriter. How does that help us? PrintWriter s methods do not create Strings. But we can construct a PrintWriter with an OutputStream If we look through the possible OutputStream classes to choose from, we see that ByteArrayOutputStream has a tostring() method... ( VIII ) Java IO - 14

StackTrace.toString() Bringing it all together import java.io.*; public class StackTrace { public static String tostring( Throwable t ) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter( baos ); t.printstacktrace( pw ); pw.flush(); String rc = baos.tostring(); pw.close(); return rc ; } } ( VIII ) Java IO - 15

Object cloning java.lang.object s clone() method has protected access Thus, an arbitrary block of code cannot clone any Object: Foo foo = new Foo(); Foo foo2 = foo.clone(); // won t compile, unless Foo overrides // clone() to be public. So, how can an arbitrary block of code make a copy of any Object? We could make a new interface: Copyable Foo foo = new CopyableFoo(); // implements Copyable Foo foo2 = foo.copy(); // deep or shallow copy? What if the Object (and all of its delegates) implements java.io.serializable? ( VIII ) Java IO - 16

Object cloning (cont.) // Serialize the Object into a byte[] Foo foo = new Foo(); // Foo implements java.io.serializable ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeobject( foo ); oos.flush(); byte[] foobytes = baos.tobytearray(); oos.close(); // De-Serialize the byte[] into a Foo // deep or shallow copy? ByteArrayInputStream bais = new ByteArrayInputStream( foobytes ); ObjectInputStream ois = new ObjectInputStream( bais ); Foo foo2 = (Foo) ois.readobject(); ois.close(); ( VIII ) Java IO - 17