MIT AITI 2003 Lecture 15 Streams Input and Output data from/to other sources.

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
Advertisements

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.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
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.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
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.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
CIS 068 JAVA I/O: Streams and Files. CIS 068 I/O Usual Purpose: storing data to ‘nonvolatile‘ devices, e.g. harddisk Classes provided by package java.io.
Two Ways to Store Data in a File Text format Binary format.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
CIS 270—Application Development II Chapter 14—Files and Streams.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
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.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Chapter 9-Text File I/O. Overview n Text File I/O and Streams n Writing to a file. n Reading from a file. n Parsing and tokenizing. n Random Access n.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
Two Ways to Store Data in a File  Text format  Binary format.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.
A stream is a sequence of data. A stream is a flowing sequence of characters.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Lecture 5 I/O and Parsing
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
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.
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.
Chapter 15: Input and Output
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.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
GENERICS AND FILE HANDLING Saumya Srivastava (977934) Divyangana Pandey (977790) Shubhi Saxena (978108) Arka Das (962969) AHD05/15-16 AJA 21.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
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.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
The Java IO System Different kinds of IO Different kinds of operations
Lecture 8: I/O Streams types of I/O streams Chaining Streams
IO in java.
OO Design and Programming II I/O: Reading and Writing
University of Central Florida COP 3330 Object Oriented Programming
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Streams and File I/O Chapter 14.
JAVA IO.
CHAPTER 5 (PART 2) JAVA FILE INPUT/OUTPUT
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Web Design & Development Lecture 8
CS 240 – Advanced Programming Concepts
File Input and Output.
David Davenport Spring 2005
Presentation transcript:

MIT AITI 2003 Lecture 15 Streams Input and Output data from/to other sources

Goals 1.Read bytes/characters from a file into a program 2.Create a new file 3.Write bytes/characters from a program to a file

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

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

Input vs Output Streams  We use streams to save data or retrieve data  A stream is an object that takes information from one source and sends it to another  Input streams - read data from a source  Output streams – write data to a source  If you want to read and write the same destination, you use 2 streams

Byte Streams vs. Character Streams  Byte Streams are used to read and write data in byte format (such as executable programs, word- processing documents, MP3 music files, etc)  Character Streams are used to read and write data in the form of characters – individual letters, numbers, punctuation, and the like (such as text files, word processing documents, web pages and the like).

Using streams to input/output data 1. Create a stream object associated with the data 2. Call methods of the stream to either put information in the stream or take information out of it 3. Close the stream by calling the object’s close() method

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 File System Output Stream Program Input Stream File System

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

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

Stream Pipeline – Reading I File Input Stream Input Stream Reader Buffered Reader Stream Tokenizer

Stream Pipeline – Reading 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

Stream Pipeline - Reading III FileInputStream f = new FileInputStream( path ); InputStreamReader i = new InputStreamReader( f ); BufferedReader b = new BufferedReader( i ); StreamTokenizer t = new StreamTokenizer( b );

StreamTokenizer (1)  Java supplies a special class called StreamTokenizer that accepts a Reader as a constructor argument.  It breaks the input character stream into tokens, sequences of 1 or more contiguous characters that "belong" together.  The user accesses these tokens by calling the nextToken() method, which always returns an int representing the type of the next token: –word, –number, –end of file (EOF), –end of line (EOL, optional), and –otherCharacter, returned as int value of the 16 bit character code

StreamTokenizer (2)  When a StreamTokenizer recognizes a word, the public member sval contains the String representing the word.  When a number token is recognized, public member nval contains its value.  StreamTokenizer also ignores whitespace (blanks and tabs) and C, C++, and Java style comments by default.  StreamTokenizer instance methods can change the definition of “word” or “number” and can turn on or off features like ignoring comments.

StringTokenizer  Similarly, a StringTokenizer breaks a string into tokens.  The tokenization method is much simpler than the one used by the StreamTokenizer class.  The following is one example of the use of the tokenizer. The code: StringTokenizer st = new StringTokenizer("this is a test"); while (st.hasMoreTokens()) { println(st.nextToken()); } prints the following output: this is a test

Reading primitive Java data types File Input Stream Data Input Stream  A FileInputStream reads bytes from a file  An DataInputStream reads primitive Java data types from a byte stream in a machine-independent way.

Reading character files Buffered Reader Stream Tokenizer  A FileReader reads a character stream from a file (equivalent to a InputStreamReader on a FileInputStream, assuming the default character encoding and the default byte-buffer size are appropriate)  A BufferedReader buffers a character stream for efficiency  A StreamTokenizer parses a character stream into tokens File Reader

Stream Pipeline – Writing I Buffered Writer Ouput Stream Writer File Output Stream

Stream Pipeline – Writing II  A BufferedWriter buffers a character stream for efficiency (buffering characters so as to provide for the efficient writing of single characters, arrays, and strings)  A OuputStreamWriter converts characters to a byte stream according to a specified character encoding. (The encoding that it uses may be specified by name, or the platform's default encoding may be accepted. )  A FileOutputStream writes bytes to a file

Write to a byte file  A DataOutputStream writes primitive Java data types to a byte stream.  A FileOutputStream writes bytes to a file. Data Output Stream File Output Stream

Write to a character file  A PrintWriter print formatted representations of objects to a text-output stream  A FileWriter writes to character files. Print Writer File Writer

A slightly complicated example  First File: Employee_May.dat Name, SSN, hourly rate, salary to date Paul Njoroge, , 65, Evelyn Eastmond, , 70, Peilei Fan, , 60, Ethan Howe, , 80, Naveen Goela, , 75,  Second file: Hours.dat, contains 5 integers, which are the number of hours each employee has worked for that month. The integers have the same sequence as that of the employee records. Content:

What we need to do: Our program 1. reads the number of hours worked from Hours.dat, 2. calculates the monthly salary for that employee, 3. updates her salary to date, 4. and print the new data to a file called Employee_June.dat

Five steps for the program 1. Import the Headers 2. Read the Data File (Hours.dat) 3. Read the Text File (Employee_May.dat) 4. Update the Data 5. Output the File

1. Import the Headers  import java.io.*;  import java.util.*;

2. Read the Data File (Hours.dat)  1. Create a File object representing Hours.dat  2. Connect the file object to an input stream (FileInputStream)  3. Attach a filter stream (DataInputStream) to the input stream  4. Read 5 integers from the data input stream (call readInt() method of DataInputStream)  5. Close the input stream File f = new File("Hours.dat"); FileInputStream fin= new FileInputStream(f); DataInputStream din = new DataInputStream(fin); int[] hours = new int[10]; for (int i=0; i<5; i++) hours[i] = din.readInt(); din.close();

3. Read the Text File (Employee_May.dat)  6. Connect Employee_May.dat to a FileReader  7. Attach a BufferedReader to the file reader  8. Read 5 strings from the buffered reader  9. Close the buffered reader FileReader fr = new FileReader("Employee_May.dat"); BufferedReader in = new BufferedReader(fr); String[] records = new String[5]; for (int j=0; j<5; j++) records[j] = in.readLine(); in.close();

4. Update the Data (steps)  The readLine() function return a string that contains all 4 fields of an employee record. We need to find the hourly rate and salary to date.  10. Assign the string to a StringTokenizer  11. Find the 3rd and 4th tokens in the string  12. Calculate the salary for this month and add it to the salary to date  In this process, we used a utility class called StringTokenizer which breaks the string into individual pieces (tokens) based on the delimiter. In our example,the delimiter is ", "

4. Update the Data (code) StringTokenizer st; String name, ssn; double hourlyRate, salary; for (int k=0; k<5; k++) { st = new StringTokenizer(records[k], ", "); name = st.nextToken(); ssn = st.nextToken(); hourlyRate = Double.parseDouble(st.nextToken()); salary = Double.parseDouble(st.nextToken()); salary += hourlyRate * hours[k]; records[k] = name + ", " + ssn + ", " + hourlyRate + ", " + salary }

5. Output the Data  13. Create a new FileWriter with the file name Employee_June.dat  14. Attach a PrintWriter to the file writer  15. Write the string array to the PrintWriter  16. Close the PrintWriter FileWriter fw = new FileWriter("Employee_June.dat"); PrintWriter out = new PrintWriter(fw); for (int i=0; i<5; i++) out.println(records[i]); out.close();

Pop Quiz  What package do you need to import in order to write/read a file?  What package do you need to import in order to use StringTokenizer?  To read a byte file, what pipes do you need to use, for instance, read a byte file “MyInt.dat” which contains integer data types?  To read a text file (“MyText.txt”), what pipes do you need to use?

Pop Quiz (2) 1. What do you need to use to write a text file? 2. What do you need to use to write a byte file? 3. Can you use a text editor such as word pad, note pad, or microsoft word to see the content of a byte file? What about a text file? 4. Do you know the name of the person who sits next to you? 5. What kind of Exception do you have to deal with when you read/write a file? How are you going to deal with it?