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.

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

I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 18 Binary I/O.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
COMP201 Java Programming Topic 6: Streams and Files Reading: Chapter 12.
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.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java I/O Input: information brought to program from an external source
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
Streams and Files CMPS Overview Stream classes File objects File operations with streams Examples in C++ and Java 2.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Chapter 17 Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams  Use JFileChooser F Text Input.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
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.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Applications Development Input and Output in Java Topics covered: Some input-output capabilities of Java Example input code Java.
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.
L5: Input & Output COMP206, Geoff Holmes and Bernhard Pfahringer.
Two Ways to Store Data in a File  Text format  Binary format.
Java Input/Output. Reading standard input Surprisingly complicated (GUI focus) Old-fashioned way: BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
© 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.
1 CISC 370: I/O Streams James Atlas June 24, 2008.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Copyright(c) Systems and Computer Engineering, Carleton Univeristy, * Object-Oriented Software Development Unit 13 I/O Stream Hierarchy Case.
Streams & Files. Java I/O Classes Saving data to / Loading data from files Two Choices: Binary-Formatted or Text-Formatted Data – int x = 1234; – Binary.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Binary I/O.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
1 Chapter 19 Binary I/O. 2 Motivations F Data stored in a text file – is represented in human-readable form –Text file –Readable –Java source programs.
Chapter 15: Input and Output
Company Input/Output Stream –. Input/Output Stream Data Program Input Stream Output Stream.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
java.io supports console and file I/O
Fundamental of Java Programming
IO in java.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
CSG2H3 Object Oriented Programming
IO in java.
Chapter 17 Input and Output
Chapter 17 Binary I/O.
I/O Basics.
Chapter 17 Binary I/O 1.
File.
Programming in Java Files and I/O Streams
Files and Streams in Java
CS 240 – Advanced Programming Concepts
Streams and Readers The stream hierarchy is for reading bytes, the reader/writer hierarchy is for reading characters Unicode characters can be used internationally,
David Davenport Spring 2005
Presentation transcript:

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 java.io.*

Department of Computer Science2 Overview IO provides communication with devices (files, console, networks etc.) Communication varies (sequential, random-access, binary, char, lines, words, objects, …) Java provides a “mix and match” solution based around byte-oriented and character-oriented I/O streams – ordered sequences of data (bytes or chars). System streams System.in, (out and err) are available to all Java programs (console I/O) – System.in is an instance of the InputStream class, System.out is an instance of PrintStream So I/O involves creating appropriate stream objects for your task.

Department of Computer Science3 The IO Zoo More than 60 different stream types. Based around four abstract classes: InputStream, OutputStream, Reader and Writer. Unicode characters (two bytes per char) are dealt with separately with Reader/Writers (and their subclasses). Byte oriented I/O is dealt with by InputStream, OutputStream and their subclasses.

Department of Computer Science4 Reading Bytes Abstract classes provide basic common operations which are used as the foundation for more concrete classes, eg InputStream has int read( ) - reads a byte and returns it or –1 (end of input) int available( ) – num of bytes still to read void close() Concrete classes override this method, eg FileInputStream reads one byte from a file, System.in is a subclass of InputStream that allows you to read from the keyboard

Department of Computer Science5 InputStream hierarchy InputStream ByteArray File Filter Piped Object Sequence InputStream InputStream InputStream Data Buffered LineNumber PushBack InputStream InputStream InputStream InputStream

Department of Computer Science6 Writing Bytes void write(int b) - writes a single byte to an output location. Java IO programs involve using concrete versions of these because most data contain numbers, strings and objects rather than individual bytes

Department of Computer Science7 OutputStream hierachy OutputStream ByteArray File Filter Piped Object OutputStream OutputStream OutputStream OutputStream OutputStream Data Buffered PrintStream OutputStream OutputStream

Department of Computer Science8 File Processing Typical pattern for file processing is: OPEN A FILE CHECK FILE OPENED READ/WRITE FROM/TO FILE CLOSE FILE Input and Output streams have close method (output may also use flush)

Department of Computer Science9 File IO Streams FileInputStream and FileOutputStream give you IO from a disk file FileInputStream fin = new FileInputStream(“in.txt”); We can now read bytes from a file but not much else! To get a file stream that can process data means combining two streams into a filtered stream (here using DataInputStream): FileInputStream fin = new FileInputStream(“in.txt”); DataInputStream din = new DataInputStream(fin); double s = din.readDouble(); // better interface to file!

Department of Computer Science10 Buffering By default streams are not buffered, so every read or write results in a call to the OS (= very slow!). Adding buffering means chaining streams: DataInputStream din = new DataInputStream( new BufferedInputStream( new FileInputStream(“in.txt”))); DataInputStream is last in the chain here because we want to use its methods and we want them to use the buffered methods (eg read).

Department of Computer Science11 File I/O Streams Constructors FileInputStream(String name) FileOutputStream(String name) BufferedInputStream(InputStream in) BufferedOutputStream(OutputStream out)

Department of Computer Science12 Random Access Streams Files are normally processed from start to end but this can be time consuming (recall that streams are sequences of bytes). To find (or write) data anywhere in a file we can use a RandomAccessFile stream class. RandomAccessFile in = new RandomAccessFile(“in.dat”,”r”); RandomAccessFile out = new RandomAccessFile(“out.dat”,”rw”); A useful method is “seek(long pos)” that allows you to move the file pointer to a byte position in the file and start reading from their.

Department of Computer Science13 Text Streams Character IO is done using subclasses of the abstract classes Reader and Writer. To write text we use the PrintWriter class: Example: PrintWriter out = new PrintWriter( new FileWriter(“out.txt”)); String name = “Fred Jones”; double score = 240.5; out.print(name); out.print(‘ ‘); out.println(score);// writes Fred Jones 240.5

Department of Computer Science14 Reading Text To write data in binary format we use DataOutputStream To write data in text format we use PrintWriter Is there a DataInputStream that lets you read in data as text? Sadly, the answer is NO! Text input is done using a BufferedReader: BufferedReader in = new BufferedReader(new FileReader(“in.txt”)); String s; while ((s = in.readLine() ) != null) { do something with s; }

Department of Computer Science15 Putting Streams to Use We will look at a standard file processing example using arrays of records (“Scores”): First as a file of text records: Chris Harris, 135, India public void writeScores(PrintWriter os) throws IOException { os.println(name + ‘,’ + highScore + “,” + country); }

Department of Computer Science16 Reading back the scores We use the BufferedReader (readLine) combination to get the output back in: BufferedReader in = new BufferedReader(new FileReader(“scores.dat”)); public void readScores(BufferedReader is) throws IOException { String s = is.readLine( );// need to break up line! } If we had a class called Scores then we could add the writeScores and readScores methods to its definition.

Department of Computer Science17 Example Program 1 DataFileTest Breaking up lines is done with a Stream Tokenizer which will be dealt with later. Define class Scores (object holding data to be read or written) The object writes/reads itself Create an array of objects and have them individually read/write themselves

Department of Computer Science18 Object Streams So far we have dealt with fixed length records, what if we treat the classes as objects and write them all to disk. To save object data we need to open an ObjectOutputStream object: ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(“scores.dat”)); Now saving objects is easier using writeObject and readObject.

Department of Computer Science19 Example 2 - ObjectFileTest The previous code can be simplified if we rewrite it using object streams – now the array of records can be written/read in one single operation Note: we have to make the Scores class implement the Serializable interface. The serialization file format is more expensive than the text format.

Department of Computer Science20 Serialization is smart Consider class Employee { String name; Double salary; } Class Manager extends Employee { private Employee secretary; // do super trick on manager constructor to init }