Active Learning: Streams

Similar documents
1.00 Lecture 30. Sending information to a Java program

Files and Streams

CS 251 Intermediate Programming Java I/O Streams

Class 26: Linked Lists

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

Chapter 12. File Input and Output. CS180-Recitation

Object-Oriented Programming in the Java language

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

Core Java Contents. Duration: 25 Hours (1 Month)

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

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

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

Exceptions and Working with Files

Training topic: OCPJP (Oracle certified professional Java programmer) or SCJP (Sun certified Java programmer) Content and Objectives

JAVA. Duration: 2 Months

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7)

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

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

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

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

CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams

Example: Copying the contents of a file

Core Java Syllabus DAY -1 :

Data Structures. 03 Streams & File I/O

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

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

CS112 Lecture: Streams

Object Oriented Programming CS104 LTPC:

Core Java Syllabus. Overview

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

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

CPS122 Lecture: Input-Output

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

Job Migration. Job Migration

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

104. Intermediate Java Programming

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

CPS122 Lecture: Input-Output

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

Complete Java Contents

PIC 20A Streams and I/O

Lecture 7. File Processing

JAVA. 1. Introduction to JAVA

Darshan Institute of Engineering & Technology for Diploma Studies

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

HST 952. Computing for Biomedical Scientists Lecture 8

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

1.00 Lecture 31. Streams 2. Reading for next time: Big Java , The 3 Flavors of Streams

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Chapter 10. IO Streams

Chapter 11: Exceptions and Advanced File I/O

Question 1. (2 points) What is the difference between a stream and a file?

Chapter 12: Exceptions and Advanced File I/O

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Streams and File I/O

Lab 5: Java IO 12:00 PM, Feb 21, 2018

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

I/O Streams. Object-oriented programming

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

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

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

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

Mathematics/Science Department Kirkwood Community College. Course Syllabus. Computer Science CSC142 1/10

Lecture 4. The Java Collections Framework

Lecture 11.1 I/O Streams

The Java Collections Framework. Chapters 7.5

Files and IO, Streams. JAVA Standard Edition

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

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

C17: I/O Streams and File I/O

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

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

Introduction Unit 4: Input, output and exceptions

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

Compile error. 2. A run time error occurs when the program runs and is caused by a number of reasons, such as dividing by zero.

C17: File I/O and Exception Handling

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

CSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7. Question 1. (2 points) What is the difference between a stream and a file?

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.

Software 1. Java I/O

CN208 Introduction to Computer Programming

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

CSC 1214: Object-Oriented Programming

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

Object-Oriented Programming Design. Topic : Streams and Files

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

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

Streams and File I/O

A- Core Java Audience Prerequisites Approach Objectives 1. Introduction

Graduate-Credit Programming Project

File Input and Output Recitation 04/03/2009. CS 180 Department of Computer Science, Purdue University

Contents Chapter 1 Introduction to Programming and the Java Language

Implementing a List in Java. CSC 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List CSC

Objec&ves. Review. Standard Error Streams

Performing input and output operations using a Byte Stream

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

List ADT. Announcements. The List interface. Implementing the List ADT

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

Fundamental language mechanisms

Transcription:

Lecture 29 Active Learning: Streams The Logger Application 2 1

Goals Using the framework of the Logger application, we are going to explore three ways to read and write data using Java streams: 1. as text 2. as binary data 3. as serialized objects We're going to learn how to use Java's built in LinkedList class and its helper class ListIterator to maintain the log. 3 Logger Architecture Logger.java: provides main() and GUI generates log data ("Log") as Date objects summarizes and performs minimal validity check ("Summarize"); selects Files for reading and writing using a JFileChooser calls methods in LoggerIO to perform reading and writing of data You are going to write those methods. 4 2

java.util.linkedlist java.util.linkedlist possesses the same methods as our SLinkedList and many others. Logger uses a LinkedList to hold the log data, and it passes the list in calls to the LoggerIO methods you will have to write. For instance: void savetotext( List list, File f ) 5 Iterators An iterator is a helper class designed to be used with a List or other collection class. It has methods to return the collection's members one at a time. Iterators can also implement methods that allow the collection to be modified relative to the current position of the iterator. 6 3

ListIterator Interface public interface ListIterator { public boolean hasnext(); public Object next() throws NoSuchElementException; public boolean hasprevious(); public Object previous() throws NoSuchElementException; public void remove() throws IllegalStateException; public void add( Object o ); public void set( Object o ) throws IllegalStateException.... } 7 Iterator Methods Java iterators return a new element and advance to the next with the same operation, next(). The Java ListIterator also allows you to go backwards ( hasprevious() and previous() ). The most recent element returned by next() is the current element. remove() will delete the current element from the underlying collection. set() will change it. add() will insert a new element after the current element and before the element that would be returned by the following call to next(). After a call to add(), the inserted element becomes the new current. A call to next() will return the element after the inserted one. The first call to next() should return the first element of the list. 8 4

Using an Iterator List mylist = new LinkedList();... ListIterator iter = mylist.listiterator();... while ( iter.hasnext() ) { Object o = iter.next();... } 9 Traditional I/O The traditional approach uses different schemes depending on the type of the source or destination, e.g., keyboard input screen output files interprocess pipes network sockets 10 5

Java I/O Java s preferred approach is to handle I/O using streams (pioneered in C++) Java provides set of abstract stream classes that define the stream interfaces hierarchy of stream implementations Java allows you to treat some I/O distinctively, e.g. RandomAccessFile 11 Input vs Output Streams Streams are unidirectional An input stream controls data coming into the program from some source An output stream controls data leaving the program for some destination If you want to read and write the same destination, you use 2 streams 12 6

Streams and I/O Channels Usually the other end of a stream leads to or arises from a platform-specific media service, for instance, a file system Input Stream Output Stream File System Program File System 13 What Streams Share Java Streams are FIFO queues Streams deliver information in the order it was inserted into the underlying channel Standard Java streams only provide sequential access without rewind, backup, or random access 14 7

Coupling Streams Java streams may be combined by using one stream as a constructor argument to another This is usually done to add functionality and/or convert the data Stream pipelines are constructed from the data source to the program or from the data destination back to the program 15 Stream Pipeline, I File Input Stream Input Stream Reader Buffered Reader Stream Tokenizer 16 8

Stream Pipeline, II A FileInputStream reads bytes from a file An InputStreamReader converts a byte stream to characters A BufferedReader buffers a character stream for efficiency A StreamTokenizer parses a character stream into tokens 17 Constructing the Pipeline FileInputStream f = new FileInputStream( path ); InputStreamReader i = new InputStreamReader( f ); BufferedReader b = new BufferedReader( i ); StreamTokenizer t = new StreamTokenizer( b ); 18 9

Logger Exercise Download the two files Logger.java and LoggerIO.java from the class web site (links from Lecture 29). Save them both to a new directory. Create a new project and mount the directory into which you just saved the two java files. Don't insert package declarations. Leave them in the default package. Compile the project and test it. Try to save to a file in text mode. Did you create a file? Was there anything in it? (Look at it with Notepad). 19 savetotext() We have given you almost the whole savetotext() method; get a sense of the pattern: The try/catch blocks How we construct the stream, a FileWriter in this case How we iterate down the list How we close the stream when we are done (closing the stream saves the file) Find the method in FileWriter to write the date String and use it to output nstring on writer. Test it. Look at what you wrote using Notepad. 20 10

loadfromtext(), 1 Now proceed to the loadfromtext() method. Once again observe the pattern: Construct a BufferedReader from a FileReader; we need a BufferedReader to read lines of text at a time; Look at the while condition; we read the next line and check for EOF in one statement. Many input stream read methods return a special value when they reach the end of file. Understand why we use nested try/catch blocks and multiple catch clauses. Write a line of code to convert the line of text to a Date using Date parse( String s ) throws ParseException 21 loadfromtext(), 2 Write a second line of code to add the Date to the list the method returns. Get rid of the line (its only there to provide a dummy exception throw before you write the real code): if ( false ) throw new ParseException("",0); Test the code. Write data out, clear the logger, and see if you can load it back in in text mode. Use Notepad to hand write a new logger entry using the date pattern of the previous entries. See if you can read in the modified data. Check it with the Summarize command. 22 11

savetodata(), 1 At the heart of the Date object is a private long data field, the number of milliseconds since 12:00 am 1 Jan 1970. savetodata() saves log times as longs instead of Strings. You can retrieve the long using the Date method long gettime(). You will need to construct a DataOutputStream in order to access methods that can write longs. You can't construct one directly from a File. You will need to construct a FileOutputStream first. 23 savetodata(), 2 UsesaveToText() as a model for the rest of the method. Remember to catch exceptions. Now test. Trying writing out the same set of log times as text and data in separate files. Look at both in Notepad. Check the length of both files (you can get an exact byte count by choosing Properties from the right button menu in Explorer). 24 12

loadfromdata(), 1 Write a while loop to read longs from the DataInputStream as long as there are any (check the documentation), to convert each to a Date (there is a Date(long) constructor), and to add the Date to the return list. Pay special attention to what happens when you run out of longs in the input stream. How can you exit the while loop? Compile and test. 25 loadfromdata(), 2 Make sure you can write log data out in Data mode, clear the logger, and read the same data back in. Can you create log data in this format using Notepad? Can you read data written in Data mode back in as text? Can you read Text mode data back in as data? Why? 26 13

savetoobject(), 1 In this method, we will write out the whole List of Dates as a single object using an ObjectOutputStream. Check the documentation on how to create an ObjectOutputStream and how to call the writeobject() method. This single call will write the list and everything on it. We will look at how this works in the next lecture. Compile and test. Write out some log data in Object mode and look at it in Notepad. Check the length of the file. How does it compare to Text and Data mode. 27 loadfromobject() Write the contents of the try/catch block to read the entire log list in using an ObjectInputStream. You will have to construct the stream, call readobject(), and then close the stream. Compile and test. Can you read back in a log list that you previously wrote out in Object mode? Can you read data in Text or Data mode back in using Object mode? What are the comparative advantages of each data mode? 28 14