Lecture 15: I/O and Parsing

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
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.
1 StringBuffer & StringTokenizer Classes Chapter 5 - Other String Classes.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
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.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
CS 206 Introduction to Computer Science II 01 / 23 / 2009 Instructor: Michael Eckmann.
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/
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.
Two Ways to Store Data in a File Text format Binary format.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
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.
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.
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.
MIT AITI 2003 Lecture 15 Streams Input and Output data from/to other sources.
I/O in Java Dennis Burford
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.
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.
Chapter 15 Text Processing and File Input/Output Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
Two Ways to Store Data in a File  Text format  Binary format.
Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
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.
Chapter 9 1 Chapter 9 – Part 2 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.
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.
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.
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.
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 I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
CS 116 Object Oriented Programming II Lecture 11 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
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.
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
OO Design and Programming II I/O: Reading and Writing
Lesson 8: More File I/O February 5, 2008
I/O Streams A stream is a sequence of bytes that flows from a source to a destination In a program, we read information from an input stream and write.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Streams and File I/O Chapter 14.
JAVA IO.
18 File i/o, Parsing.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Web Design & Development Lecture 8
File Input and Output.
Presentation transcript:

Lecture 15: I/O and Parsing MIT AITI Lecture 15: I/O and Parsing Kenya 2005

What we will learn in this Lecture. This Lecture is divided into 2 main parts: I – Input /Output: Input vs Output, and Byte vs Character Streams Important Stream Classes and Using these Classes Example of Reading from and Writing to Text Files Example of Reading text from Keyboard input Using buffered streams II – Introduction to Parsing: Delimiters StringTokenizer

I/O Basics I/O = Input/Output – Communication between a computer program and external sources or destinations of information Involves: - Reading input from a source - Writing output to a destination Reading and Writing is specified by 4 abstract classes: - Reader - Writer - InputStream - OutputStream

Java I/O Streams Java programs communicate with the outside world using Streams Streams are used for reading and writing data I/O Streams are unidirectional Input stream for data coming into program Output stream for data leaving program Examples of Sources and Destinations of info include: Files, Network connections, other programs, etc.

Input vs Output Streams An object from which we can read data is an Input Stream read write An object to which we can write data is an Output Stream Info Stream Info Stream Input Stream (Source) Output Stream (Destination) Program

Byte vs. Character Streams Byte Streams are used to read and write data which is in binary format (1's and 0's) e.g. images, sounds, etc. Character Streams are used to read and write data which is in text format (characters) e.g. plain text files, web pages, user keyboard input, etc.

Important Stream Classes FileInputStream Read data in binary format from files FileOutputStream Write data in binary format to files FileReader Read text data from files FileWriter - Write text data to files

Using a Stream class Open a stream by instantiating a new stream object While more information to read/write, read/write that data using methods in the Stream Classes Close the stream by calling the object’s close() method

Java I/O Classes The java.io package offers classes used to read/write data from/to files To read/write data, we instantiate a subclass of one of the 4 abstract superclasses: input output byte InputStream OutputStream character Reader Writer

Using Reader Recall: a Reader is used to read a character input stream Reader offers methods to read single characters and arrays of characters. E.g. int read() Reader is abstract so you must instantiate a subclass of it to use these methods

Reading from a Text File public void readFile() { FileReader fileReader = null; try { fileReader = new FileReader("input.txt"); int c = fileReader.read(); while (c != -1) { char d = ((char)c); c = fileReader.read(); } } catch (FileNotFoundException e) { System.out.println("File was not found"); } catch (IOException e) { System.out.println("Error reading from file"); if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { /* ignore */ } Step 1  Step 2 Step 3 

BufferedReader BufferedReader is a subclass of Reader Buffers the character stream from FileReader and has readLine() method to read an entire line of characters efficiently FileReader fr = new FileReader("myFile.txt"); BufferedReader br = new BufferedReader(fr); The readLine() method returns null when there are no more lines to read

Using BufferedReader public void readFileWithBufferedReader() { BufferedReader bufferedReader = null; try { FileReader fr = new FileReader("input.txt"); bufferedReader = new BufferedReader(fr); String line = bufferedReader.readLine(); while (line != null) { // do something with line line = bufferedReader.readLine(); } } catch (FileNotFoundException e) { System.out.println("File was not found"); } catch (IOException e) { System.out.println("Error reading from file"); if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { /* ignore */ }

POP QUIZ Why can we not create instances of the Reader class directly? Which kind of stream would we use to read/write data in binary format? Which kind of stream would we use to read/write data in text format? Why do we wrap a FileReader with a BufferedReader before reading from a Text file? Reader is an Abstract class, and cannot be instantiated Byte Streams Character Streams BufferedReader has the readLine() method used to read entire lines

Writer Writer is an abstract class used to write to character streams Offers write methods to write single characters, arrays of characters, and strings (look at API) e.g. void write(int c) BufferedWriter (subclass of Writer) offers efficient writing; newLine() method to insert a blank line and write(String n) method to write data Close Writer with close() method when done

Writing to a Text File public void writeFileWithBufferedWriter() { BufferedWriter buffWriter = null; try { FileWriter fw = new FileWriter("output.txt"); buffWriter = new BufferedWriter(fw); while (/*still stuff to write */) { String line = // get line to write buffWriter.write(line); buffWriter.newLine(); } } catch (IOException e) { System.out.println("Error writing to file"); if (buffWriter != null) { try { buffWriter.close(); } catch(IOException e) { /* ignore */ }

Example: Copying Text Files void copyFiles(String inFilename, String outFilename) throws FileNotFoundException { BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader(inFilename)); bw = new BufferedWriter(new FileWriter(outFilename)); String line = br.readLine(); while(line != null) { bw.write(line); bw.newLine(); line = br.readLine(); } } catch (IOException e) { System.out.println("Error copying files"); if (br != null) {try {br.close();} catch(IOException e) {}} if (bw != null) {try {bw.close();} catch(IOException e) {}}

Reading From Keyboard Input Keyboard input is sent over a Stream referred to as "standard" input, but to read the data you want it to be a Reader InputStream acts as a crossover class, to get from a Stream to a Reader To read characters over an InputStream, need to wrap it in an InputStreamReader To read line by line, wrap the InputStreamReader with a BufferedReader

Example: Reading from Keyboard Input /** * Returns a line read from keyboard input. * Return null if there was an error reading the line. */ public void String readKeyboardLine() throws IOException { BufferedReader br = null; String line = null; try { br = new BufferedReader(new InputStreamReader(System.in)); line = br.readLine(); } catch (IOException e) {} if (br != null) { try { br.close(); } catch (IOException e) { /* ignore */ } } return line;

Streams Conclusion Make sure you look at the InputStream and OutputStream hierarchy, and Reader and Writer hierarchy in a Java Textbook to see their subclasses and methods Use Java API!!!

Introduction to Parsing Programs often encode data in text format before it is stored in files Programs later need to decode the text in the files back into the original data Process of decoding text back into data is known as parsing

Delimiters When data is stored in text format, delimiter characters are used to separate tokens (or pieces) of the data A list of first names stored separated by the '#' delimiter: Greg#Kwame#Sonya#Bobby Same list with a newline delimiter: Greg Kwame Sonya Other common delimiters are ‘|’ ‘:’

StringTokenizer I When trying to read a line of input, we get one long string. We need to find the delimiters in the long string and separate out each of the individual pieces of information (tokens) For this, we use the StringTokenizer class in java.util

StringTokenizer I When constructing the tokenizer object, you can specify which characters are the delimiters in your case Default constructor will assume “ \t\n\r” to be delimiters StringTokenizer r = new StringTokenizer(line); Second constructor accepts String of any delimiter characters String line = myFile.readline(); StringTokenizer t = new StringTokenizer(line, “#”); StringTokenizer s = new StringTokenizer(line, “,\&\|”);

StringTokenizer II - Useful StringTokenizer methods: String nextToken() method returns the next data token between delimiters in the text boolean hasMoreTokens() returns true if the text has remaining tokens

Using StringTokenizer Printing out every name from a file where names are delimited by whitespace: public void printNamesFromFile(String filename) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filename)); String line = br.readLine(); while(line != null) { StringTokenizer st = new StringTokenizer(line); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); } line = br.readLine(); } catch (IOException e) { System.out.println("Error reading from file."); if (br != null) { try { br.close(); } catch(IOException e) {} }

Parsing Numbers Often necessary to parse numbers stored as text into Java primitives Wrapper classes for primitives provide static methods to do so int Integer.parseInt(String s) double Double.parseDouble(String s) Throw NumberFormatException if the specified String cannot be converted into the primitive