1 Tirgul no. 13 Topics covered: H String parsing. H Text file I/O. H Extending Filters.

Slides:



Advertisements
Similar presentations
Lecture 15: I/O and Parsing
Advertisements

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.
Tim Wentz Nathaniel Smith Andrew Johnson. Files in Java Create a new file handle using: ▫new File(String pathname); Pathnames can be either relative or.
Using Processing Stream. Predefined Streams System.in InputStream used to read bytes from the keyboard System.out PrintStream used to write bytes to the.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Exception examples. import java.io.*; import java.util.*; class IO { private String line; private StringTokenizer tokenizer; public void newline(DataInputStream.
Overview of Java I/O. Stream A Program often needs to read/write information from/to outer source/destination. Outer source/destination can be : –A File.
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
String Tokenization What is String Tokenization?
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 StringTokenizer and StringBuffer classes Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples l StringBuffer class.
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
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.
Java Review 2. The Agenda The following topics were highlighted to me as issues: –File IO (Rem) –Wrappers (Rem) –Interfaces (Rem) –Asymptotic Notation.
Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 Files.
2-1 CM0551 Week 3 The scanner class – file input A Spelling Checker Time and space requirements for various dictionary structures.
פיתוח מונחה עצמים – שפת JAVA קבצים. References קורס "שיטות בהנדסת תוכנה", הפקולטה למדעי המחשב, הטכניון. קורס "מערכות מידע מבוזרות", הפקולטה להנדסת תעשייה.
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with.
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.
Streams and Files CMPS Overview Stream classes File objects File operations with streams Examples in C++ and Java 2.
Two Ways to Store Data in a File Text format Binary format.
Chapter 10 Exceptions and File I/O. © 2004 Pearson Addison-Wesley. All rights reserved10-2 Exceptions Exception handling is an important aspect of object-oriented.
Session 05 Java Strings and Files. Exercise Complete the “quick-and-dirty” class CharacterCounter containing only a main() method that displays the number.
1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination of.
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.
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
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.
I/O in Java Dennis Burford
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
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.
File IO Basics By Dan Fleck Coming up: Data Streams.
1 StringTokenization Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples.
Two Ways to Store Data in a File  Text format  Binary format.
Lab 2 Primer Assignment 3 Structure File I/O More parsing and HTTP Formatting.
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.
1 CHAPTER 3 StringTokenizer. 2 StringTokenizer CLASS There are BufferedReader methods to read a line (i.e. a record) and a character, but not just a single.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
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.
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.
Lecture 5 I/O and Parsing
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.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
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.
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.
Lab 04-2 Objectives:  Understand what a file is.  Learn how to use the File class  Learn how to use the Scanner class to read from files  Learn about.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
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.
More on Basic File Input ( ) Frank Ducrest.
Lesson 8: More File I/O February 5, 2008
Introduction to programming in java
Object Writing in files
CHAPTER 5 JAVA FILE INPUT/OUTPUT
Streams and File I/O Chapter 9 Chapter 9.
Streams and File I/O Chapter 14.
Reading and Writing Text Files
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
File Input and Output.
Presentation transcript:

1 Tirgul no. 13 Topics covered: H String parsing. H Text file I/O. H Extending Filters.

2 Parsing Strings  Many different tasks involve taking a string and parsing it into Tokens.  A Token is a part of the string.  Tokens are separated by Delimeters.  a Delimeter can be any char. Examples: space, \n  Tokens may be separated by many delimeters: “I have a car”

3 Parsing Strings (contd.)  We can define more than one Delimeter. For example many times the Delimiters may be all White Space characters: space \n \t \r  The package java.util includes a class called StringTokenizer that makes it easy to parse a string into tokens.  The StringTokenizer’s default delimiter list is all whitespace characters.  The simple constructor receives the String to be parsed: StringTokenizer tokenizer; tokenizer = new StringTokenizer(sentence);

4 StringTokenizer  The method nextToken reads the next Token from the String and returns it as a String: String word= tokenizer.nextToken();  All delimeter characters (by default whitespace chars) are ignored. The word returned is a sequence of all non delimiter characters from the current position – up to the first delimiter char.

5 StringTokenizer (contd.)  For example consider the sentence: “This is a lovelyday to go out“ Assuming that the delimiters are whitespace chars this sentence contains 8 Tokens: This,is,a,lovely,day,to,go,out. All other chars in the sentence are whitespace and the StringTokenizer will not include these in the tokens that it returns.

6 StringTokenizer Example import java.util.*; //so we can use the StringTokenizer class public class SentenceParser{ public static void main(String[] args){ System.out.print(“Please enter a sentence: “); String sentence= EasyInput.readString(); //init a StringTokenizer object that we will use //to parse the sentence. StringTokenizer tokenizer= new StringTokenizer(sentence); while( tokenizer.hasMoreTokens() ){ String word= tokenizer.nextToken(); System.out.println(word); }

7 Reading Text from Files BufferedReader Requires the following import: import java.io.BufferedReader; or import java.io.*; Construction: public BufferedReader(Reader in) {…} Create a buffering character-input stream that uses a default-sized input buffer. Line Reading: public String readLine() throws IOException {…} Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed. Returns a String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.

8 Reading Text from Files (contd.) FileReader Requires the following import: import java.io.FileReader; or import java.io.*; Construction: public FileReader(String fileName) throws FileNotFoundException {…} Creates a new FileReader, given the name of the file to read from.

9 Reading Text from Files Example import java.io.*; import java.util.StringTokenizer; try { int lineNum, wordNum; String line; BufferedReader inStream = new BufferedReader(new FileReader(args[0])); lineNum = wordNum = 0; do { line = inStream.readLine(); if(line != null) { lineNum++; StringTokenizer st = new StringTokenizer(line,args[1]); wordNum += st.countTokens(); } }while(line != null); System.out.println("There are " + lineNum + " lines."); System.out.println("There are " + wordNum + " words."); }catch(FileNotFoundException fnfe) { System.out.println("File ("+ args[0] +") not found."); }catch(IOException ioe) { System.out.println("I/O error while reading file ("+ args[0] +")"); }

10 Extending Filter Classes H FilterReader and FilterWriter are filter streams that can be extended to provide new formatting of textual data. H Recall that a FilterStream is a stream that connects to other Streams and therefore can be connected to any Reader/Writer. H We will now design new Filters for reading and writing which can Translate (or encode/decode) strings.

11TranslateWriter import java.io.*; public class TranslateWriter extends FilterWriter{ private String from; private String to; private static char[] oneChar; private static char[] charArray; static{ oneChar= new char[1]; } public TranslateWriter(Writer w, String from, String to){ super(w); this.from= from; this.to= to; } public TranslateWriter(Writer w){ super(w); String upper= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String lower= "abcdefghijklmnopqrstuvwxyz"; this.from= upper + lower; this.to= lower + upper; }

12 TranslateWriter (cont.) public void write(int c) throws IOException { oneChar[0]= (char)c; write(oneChar,0,1); } public void write(char[] cbuf, int off, int len) throws IOException{ if(cbuf == null) throw new IOException(); int i; for(i=0; i<cbuf.length; i++){ int mapIndex= from.indexOf(cbuf[i]); if(mapIndex >=0) cbuf[i]= to.charAt(mapIndex); } super.write(cbuf,off,len); } public void write(String s, int off, int len) throws IOException{ if(s == null) throw new IOException(); charArray= s.toCharArray(); write(charArray,off,len); }

13 TranslateWriter (main) public static void main(String[] args){ OutputStreamWriter osw; TranslateWriter translateWriter; osw= new OutputStreamWriter(System.out); translateWriter= new TranslateWriter(osw); try{ translateWriter.write("Java is Great"); translateWriter.flush(); }catch(IOException ioe){ System.err.println(ioe); System.exit(1); }

14TranslateReader import java.io.*; public class TranslateReader extends FilterReader{ private String from; private String to; private static char[] oneChar; static{ oneChar= new char[1]; } public TranslateReader(Reader r, String from, String to){ super(r); this.from= from; this.to= to; } public TranslateReader(Reader r){ super(r); String upper= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String lower= "abcdefghijklmnopqrstuvwxyz"; this.from= upper + lower; this.to= lower + upper; }

15 TranslateReader cont. public int read() throws IOException { int result= read(oneChar,0,1); if(result < 0) return(result); else return(oneChar[0]); } public int read(char[] cbuf, int off, int len) throws IOException{ int n= super.read(cbuf,off,len); int i; for(i=0; i<n; i++){ int mapIndex= from.indexOf(cbuf[i]); if(mapIndex >=0) cbuf[i]= to.charAt(mapIndex); } return(n); }

16 TranslateReader (main) public static void main(String[] args){ StringReader sr= new StringReader("Java is Great"); TranslateReader translateReader= new TranslateReader(sr); LineNumberReader lnr= new LineNumberReader(translateReader); try{ String line= lnr.readLine(); System.out.println(line); }catch(IOException ioe){ } }//end of TranslateReader class.