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



Similar documents
INPUT AND OUTPUT STREAMS

What is an I/O Stream?

Programming in Java

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

JAVA - FILES AND I/O

CS 1302 Ch 19, Binary I/O

Readings and References. Topic #10: Java Input / Output. "Streams" are the basic I/O objects. Input & Output. Streams. The stream model A-1.

D06 PROGRAMMING with JAVA

WRITING DATA TO A BINARY FILE

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

AVRO - SERIALIZATION

Files and input/output streams

Java Fundamental Classes Reference

public static void main(string[] args) { System.out.println("hello, world"); } }

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

Input / Output Framework java.io Framework

Software Architectures

Creating a Simple, Multithreaded Chat System with Java

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

CS506 Web Design and Development Solved Online Quiz No. 01

Building a Multi-Threaded Web Server

Stream Classes and File I/O

Today s Outline. Computer Communications. Java Communications uses Streams. Wrapping Streams. Stream Conventions 2/13/2016 CSE 132

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

Principles of Software Construction: Objects, Design, and Concurrency. Design Case Study: Stream I/O Some answers. Charlie Garrod Jonathan Aldrich

Lesson: All About Sockets

Files and Streams. Writeappropriatecodetoread,writeandupdatefilesusingFileInputStream, FileOutputStream and RandomAccessFile objects.

1 of 1 24/05/ :23 AM

Object-Oriented Programming in Java

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

An Overview of Java. overview-1

Decorator Pattern [GoF]

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

The Interface Concept

13 File Output and Input

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Division of Informatics, University of Edinburgh

Event-Driven Programming

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Using Files as Input/Output in Java 5.0 Applications

Network/Socket Programming in Java. Rajkumar Buyya

Java from a C perspective. Plan

Quick Introduction to Java

Introduction to Java

Sample CSE8A midterm Multiple Choice (circle one)

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Crash Course in Java

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

Java Programming Fundamentals

Reading Input From A File

Application Development with TCP/IP. Brian S. Mitchell Drexel University

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

CSE 8B Midterm Fall 2015

Communicating with a Barco projector over network. Technical note

Pemrograman Dasar. Basic Elements Of Java

CMSC 132: Object-Oriented Programming II. Design Patterns I. Department of Computer Science University of Maryland, College Park

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

I/O Fundamentals. Notes. The File Class

Java Network. Slides prepared by : Farzana Rahman

ECE 122. Engineering Problem Solving with Java

Lecture 7: Class design for security

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

TP N 10 : Gestion des fichiers Langage JAVA

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Course Intro Instructor Intro Java Intro, Continued

Software Engineering Techniques

CS 111 Classes I 1. Software Organization View to this point:

! "# $%&'( ) * ).) "%&' 1* ( %&' ! "%&'2 (! ""$ 1! ""3($

J a v a Quiz (Unit 3, Test 0 Practice)

Objectives. Streams and File I/O. Objectives, cont. Outline. I/O Overview. Streams

Chapter 2 Introduction to Java programming

Object Oriented Software Design

Network Communication

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

COSC 6397 Big Data Analytics. Distributed File Systems (II) Edgar Gabriel Spring HDFS Basics

Remote Method Invocation

Chapter 2: Elements of Java

The following program is aiming to extract from a simple text file an analysis of the content such as:

IT6503 WEB PROGRAMMING. Unit-I

DC60 JAVA AND WEB PROGRAMMING JUNE b. Explain the meaning of the following statement public static void main (string args [ ] )

JAVA Program For Processing SMS Messages

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

AP Computer Science Java Subset

This example illustrates how to copy contents from one file to another file. This topic is related to the I/O (input/output) of

Java CPD (I) Frans Coenen Department of Computer Science

Text file I/O and simple GUI dialogues

Transcription:

Binary I/O streams (ascii, 8 bits) InputStream OutputStream The Java I/O System The decorator design pattern Character I/O streams (Unicode, 16 bits) Reader Writer Comparing Binary I/O to Character I/O Files and directories The class File Object Serialization Light-weight persistence Will only look at the package java.io not java.nio. OOP: The Java I/O System 1

Overview of The Java I/O System Goal: To provide an abstraction of all types of I/O Memory File Directory Network Express all configurations Character, binary, buffered, etc. Different kinds of operations Sequential, random access, by line, by word, etc. OOP: The Java I/O System 2

The Stream Concept A stream is a sequential source of information used to transfer information from one source to another. [Source: java.sun.com] OOP: The Java I/O System 3

Streams in Java There is a huge (and complicated) hierarchy of stream classes in Java. Overview of the stream hierarchy Reader, root in unicode input hierarchy Writer, root in unicode output hierarchy InputStream, root in binary input hierarchy OutputStream, root in binary output hierarchy All abstract classes. OOP: The Java I/O System 4

The Decorator Design Pattern Wrap classes in decorators to add functionality. Component operation() ConcretComponent operation() Decorator operation() component //addopr(); component.operation() ConcreteDecorator1 operation() addstate ConcreteDecorator2 operation() addopr() OOP: The Java I/O System 5

Two issues with I/O Decorator Pattern and Java I/O What are you talking to (n). The way you are talking to it (m). Solution no. 1 Make a class for every combination n * m classes, not flexible, hard to extend Solutions no. 2 Java filter streams (decorators) are added dynamically to create the functionality needed. n + m classes Input decorator: FilterInputStream Output decorator: FilterOutputStream OOP: The Java I/O System 6

InputStream Hierarchy [Source: java.sun.com] InputStream, the abstract component root in decorator pattern FileInputStream, etc. the concrete components FilterInputStream, the abstract decorator LineNumberInputStream, DataInputStream, etc. concrete decorators OOP: The Java I/O System 7

OutputStream Hierarchy [Source: java.sun.com] OutputStream, the abstract component root in decorator pattern FileOutputStream, etc. the concrete components FilterOutputStream, the abstract decorator PrintStream, DataOutputStream, etc. concrete decorators OOP: The Java I/O System 8

InputStream Types Type of InputStream ByteArrayInputStream StringBufferInputStream PipedInputStream FileInputStream SequencedInputStream ObjectInputStream Reads From Block of memory String (note not StringBuffer) Pipe (in another thread) File Combines InputStreams Objects from an InputStream Concrete Components OOP: The Java I/O System 9

OutputStream Types Type of OutputStream ByteArrayOutputStream PipedOutputStream FileOutputStream ObjectOutputStream Reads From Block of memory Pipe (in another thread) File Objects to a OutputStream Concrete Components OOP: The Java I/O System 10

DataInputStream FilterInputStream Full interface for reading built-in types For portable reading of data between different OS platforms BufferedInputStream Adds buffering to the stream (do this by default) LineNumberInputStream Only adds line numbers PushbackInputStream One-character push pack for scanners (lexers) Concrete Decorators OOP: The Java I/O System 11

DataOutputStream FilterOutputStream Full interface for writing built-in types For portable writing of data between different OS platforms Example: System.out.println PrintStream Allows primitive formatting of data for display (not printf!) Not for storage use DataOutputStream for this BufferedOutputStream Adds buffering to output (do this by default!) Concrete Decorators OOP: The Java I/O System 12

OutputStream, Example import java.io.*; // [Source: java.sun.com] public class DataIODemo { public static void main(string[] args) throws IOException { // where to write to DataOutputStream out = new DataOutputStream( new FileOutputStream("invoice1.txt")); // alternative also using a buffer decorator DataOutputStream out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream("invoice1.txt"))); OOP: The Java I/O System 13

OutputStream, Example, cont. import java.io.*; // [Source: java.sun.com] public class DataIODemo { public static void main(string[] args) throws IOException { snip double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int[] units = { 12, 8, 13, 29, 50 }; String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; for (int i = 0; i < prices.length; i ++) { out.writedouble(prices[i]); out.writechar('\t'); // add a tab out.writeint(units[i]); out.writechar('\t'); out.writechars(descs[i]); out.writechar('\n'); } out.close(); // add a tab // add a newline OOP: The Java I/O System 14

InputStream, Example // read it in again DataInputStream in = new DataInputStream( new FileInputStream("invoice1.txt")); // alternative also using a buffer decorator DataInputStream in = new DataInputStream( new BufferedInputStream ( new FileInputStream("invoice1.txt"))); double price; int unit; StringBuffer desc; double total = 0.0; OOP: The Java I/O System 15

InputStream, Example, cont. try { while (true) { price = in.readdouble(); in.readchar(); // throws out the tab unit = in.readint(); in.readchar(); // throws out the tab char chr; desc = new StringBuffer(20); char linesep = System.getProperty("line.separator").charAt(0); while ((chr = in.readchar())!= linesep) desc.append(chr); System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; } } catch (EOFException e) { } System.out.println("For a TOTAL of: $" + total); in.close(); } OOP: The Java I/O System 16

Reader and Writer Classes Added in Java 1.1 Not meant to replace InputStream and OutputStream Internationalization Unicode support Efficiency, designed to solved efficiency problems Structured in class hierarchies similar to the InputStream and OutputStream hierarchies Are also using the decorator design pattern OOP: The Java I/O System 17

Reader Class Hierarchy Reader, the abstract component root in decorator pattern BufferedReader, etc. the concrete components FilterReader, the abstract decorator PushbackReader, concrete decorators [Source: java.sun.com] OOP: The Java I/O System 18

Writer Class Hierarchy [Source: java.sun.com] Writer, the abstract component root in decorator pattern BufferedWriter, etc. the concrete components FilterWriter, the abstract decorator No concrete decorators OOP: The Java I/O System 19

Reader and Writer Types Transport to and from main memory CharArrayReader, CharArrayWriter StringReader, StringWriter Transport to and from pipelines (networking) PipedReader, PipedWriter Transport to and from files FileReader, FileWriter DataOutputStream unaltered from Java 1.0 to 1.1 OOP: The Java I/O System 20

InputStreamReader Character Based Streams Reads platform characters and delivers Unicode characters to the Java program. OutputStreamWriter Writes Unicode characters to platform dependent characters. PrintWriter Writes Java primitive data types to file. OOP: The Java I/O System 21

FileReader and FileWriter, Example import java.io.*; public class Copy { public static void main(string[] args) throws IOException { FileReader in = new FileReader(new File(args[0])); FileWriter out = new FileWriter(new File(args[1])); int c; do{ c = in.read(); if(c!= -1) { out.write(c); } } while (c!= -1); } } in.close(); out.close(); OOP: The Java I/O System 22

Binary vs. Character Based I/O Overview InputStream OutputStream FileInputStream FileOutputStream StringBufferedInputStream N/A ByteArrayInputStream ByteArrayOutputStream PipedInputStream PipedOutputStream Reader convert: InputStreamReader Writer convert: OutputStreamWriter FileReader FileWriter StringReader (better name) StringWriter CharArrayReader CharArrayWriter PipedReader PipedWriter OOP: The Java I/O System 23

Binary vs. Character Filter Overview FilterInputStream FilterOutputStream BufferedInputStream BufferedOutputStream DataInputStream PrintStream LineNumberInputStream PushbackInputStream FilterReader FilterWriter (abstract class) BufferedReader (has a readline()) BufferedWriter Use DataInputStream or BufferedReader PrintWriter LineNumberReader PushbackReader OOP: The Java I/O System 24

Representing the File System File systems varies between operating system, i.e., Path separators Permissions in Unix Directories on the Mac Drive letters on Windows Needs an abstraction to hide the differences To make Java program platform independent. OOP: The Java I/O System 25

The File Class Refers to one or more file names, i.e., not a handle to a file Composite design pattern To get an array of file names. Call the list() method. OOP: The Java I/O System 26

The Composite Pattern, Again Component operation() add() remove() getchild() Leaf operation() Composite operation() add() remove() getchild() children for all c in children c.operation(); OOP: The Java I/O System 27

The File Class, Example import java.io.*; public class DirectoryList { public static void main(string[] args) throws IOException{ File dir = new File(args[0]); } } if(dir.isdirectory() == false) { if (dir.exists() == false) System.out.println("There is no such dir!"); else System.out.println("That file is not a dir."); } else { String[] files = dir.list(); System.out.println ("Files in dir \"" + dir + "\":"); for (int i = 0; i < files.length; i++) System.out.println(" " + files[i]); } OOP: The Java I/O System 28

Object Serialization Very hard to do in other programming languages!!! Class must implement the Serializable interface Uses Output: ObjectOutputStream writeobject() Input: ObjectInputStream readobject() All relevant parts (the web of object) are serialized. Lightweight persistence used in RMI (send objects across a network) used in JavaBeans OOP: The Java I/O System 29

Object Serialization, Example // Write an object to disk ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("mycars.dat")); Car mytoyota = new Car(); out.writeobject(mytoyota); // Read an object from disk ObjectInputStream in = new ObjectInputStream( new FileInputStream("mycars.dat")); Car mytoyota = (Car)in.readObject(); OOP: The Java I/O System 30

Summary Streams a large class hierarchy for input and output. The decorator pattern is the key to understanding it The decorator design pattern may seem strange Very flexible, but requires extra coding in clients. There is no C-like printf functionality This is annoying For objects to live between program invocations use the Serializable interface. java.nio packages goal speed Look at it if you needed it in your projects OOP: The Java I/O System 31

FilterStream, Example import java.io.*; class StreamFilterExample{ public static void main(string[] args) throws IOException { DataInputStream din = new DataInputStream( new BufferedInputStream( new FileInputStream( new File("numbers.dat")))); int i; boolean b; i = din.readint(); b = din.readboolean(); System.out.println("i = " + i + ". b = " + b); din.close(); } } OOP: The Java I/O System 32