ISE 582: Web Technology for Industrial Engineering University of Southern California DJE Dept of Industrial and Systems Engineering Lecture 6 JAVA Cup.

Slides:



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

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.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
Files and Streams CS 21a Chapter 11 of Horstmann.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
Files and Streams CS 21a. 10/02/05 L18: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
ISE 582: Web Technology for Industrial Engineering University of Southern California DJE Dept of Industrial and Systems Engineering Lecture 7 JAVA Cup.
COMP 14 Introduction to Programming Mr. Joshua Stough February 2, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
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.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Two Ways to Store Data in a File Text format Binary format.
Session 05 Java Strings and Files. Exercise Complete the “quick-and-dirty” class CharacterCounter containing only a main() method that displays the number.
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.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
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.
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
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.
MIT AITI 2003 Lecture 15 Streams Input and Output data from/to other sources.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
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.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
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.
Characters, Strings, Reading Files CS2110, Week 2 Recitation.
Two Ways to Store Data in a File  Text format  Binary format.
CS 206 Introduction to Computer Science II 09 / 11 / 2009 Instructor: Michael Eckmann.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.
CS 11 java track: lecture 2 This week: more on object-oriented programming (OOP) objects vs. primitive types creating new objects with new calling methods.
A stream is a sequence of data. A stream is a flowing sequence of characters.
CS 321 Programming Languages and Compilers VI-a. Recursive Descent Parsing.
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
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.
Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char.
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.
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.
Learners Support Publications Working with Files.
CSI 3125, Preliminaries, page 1 Files. CSI 3125, Preliminaries, page 2 Reading and Writing Files Java provides a number of classes and methods that allow.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
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.
Object Oriented Programming Lecture 2: BallWorld.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
OO Design and Programming II I/O: Reading and Writing
Objects, Classes, Program Constructs
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
CSS161: Fundamentals of Computing
Streams and File I/O Chapter 14.
JAVA IO.
Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O
CHAPTER 5 (PART 2) JAVA FILE INPUT/OUTPUT
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O
Presentation transcript:

ISE 582: Web Technology for Industrial Engineering University of Southern California DJE Dept of Industrial and Systems Engineering Lecture 6 JAVA Cup 5: Data Structures

3 October 2002Web Technology for IE2 Handouts Lecture 6 slides READ Winston & Narasimhan : –Chapters 27-31, 33 (pp , )

3 October 2002Web Technology for IE3 JAVA Cup 5 File Access –Input file streams –Output file streams Arrays and Vectors –How to create and access arrays –Expandable vectors Characters and Strings

3 October 2002Web Technology for IE4 File Input Streams Reading files one-byte-at-a-time Taking bigger bites Java’s input-output package Traditional string handling Updating to tokens: number / words

3 October 2002Web Technology for IE5 File input streams A stream is a sequence of values. To read bytes from a file: –FileInputStream stream = new FileInputStream(“input.data”) –FileInputStream stream = new FileInputStream(“~username/public_html/ise582/input.dat a”); When you are done, it is good to: –stream.close() Reads ONE BYTE AT A TIME…

3 October 2002Web Technology for IE6 To take bigger bites than bytes To read characters from your file: –InputStreamReader reader = new InputStreamReader(stream); To read lines from your file: –BufferedReader buffer = new BufferedReader(reader); –buffer.readLine() streamreaderbuffer

3 October 2002Web Technology for IE7 Input-output package Notify JAVA that you want to work with input or output streams: –import java.io.FileInputStream –import java.io.* In the event of error –use try-catch statements –throw an exception, throws IOException

3 October 2002Web Technology for IE8 Traditional Approach Example import java.io.*; public class Demonstrate { public static void main(String argv[]) throws IOException { FileInputStream stream = new FileInputStream(“input.data”); InputStreamReader reader = new InputStreamReader(stream); BufferedReader buffer = new BufferedReader(reader); String line; while ((line=buffer.readLine())!=null && !line.equals(“”)) { System.out.println(“Line read: “ + line); } stream.close(); return; }}

3 October 2002Web Technology for IE9 String Methods line.trim() –removes white space line.indexOf(“ “) –index of first occurrence, starts from 0 line.substring(2) –returns rest of line after index 2 line.substring(0,1) Integer.parseInt(“4”) –converts string to integer

3 October 2002Web Technology for IE10 Example Continued line = line.trim(); int nextSpace = line.indexOf(" "); int x = Integer.parseInt(line.substring(0,nextSpace)); line = line.substring(nextSpace).trim(); nextSpace=line.indexOf(" "); int y = Integer.parseInt(line.substring(0,nextSpace)); line = line.substring(nextSpace).trim(); int z = Integer.parseInt(line); System.out.println("Numbers read: " + x + ", " + y + ", " + z);

3 October 2002Web Technology for IE11 The Token Approach The stream tokenizer: –StreamTokenizer tokens = new StreamTokenizer(reader); –Do away with the BufferedReader –Divides character sequences into tokens, delimited by white space Token Methods: –tokens.nextToken() –assigns value to nval, tokens.nval –always a double, if need recasting: (int) tokens.nval –end of token string indicated by TT_EOF: tokens.TT_EOF

3 October 2002Web Technology for IE12 Token Example import java.io.*; public class Demonstrate { public static void main (String argv[]) throws IOException { FileInputStream stream = new FileInputStream("input.data"); InputStreamReader reader = new InputStreamReader(stream); StreamTokenizer tokens = new StreamTokenizer(reader); while (tokens.nextToken()!= tokens.TT_EOF) { int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; Movie m = new Movie(x,y,z); System.out.println("Rating: " + m.rating()); } stream.close(); }}

3 October 2002Web Technology for IE13 Words vs. Numbers If the token is a number –nextToken returns a TT_NUMBER instance –the number is assigned to nval If the token is a word –nextToken returns a TT_WORD instance –the number is assigned to sval

3 October 2002Web Technology for IE14 Word / Number Example int next=0; while ((next=tokens.nextToken())!= tokens.TT_EOF) { switch (next) { case tokens.TT_WORD: break; case tokens.TT_NUMBER: int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; Movie m = new Movie(x,y,z); System.out.println("Rating: " + m.rating()); break; } }

3 October 2002Web Technology for IE15 Arrays and Vectors Creating / assigning values to arrays Passing arrays to methods Command-line arguments Creating vectors Vector methods Vectors as targets Using vector iterators

3 October 2002Web Technology for IE16 Creating Arrays Creating an array – [] = new [ ]; –int durations [] = new int [4]; What you can do with an array –call / assign an elt: [ ] –find its length:.length Arrays of class instances – [] = new [ ]; –Movie movies [] = new Movie [4];

3 October 2002Web Technology for IE17 Instance Array Elements Field-selection operator still works –movies[3].script = 6 Checking to see if element is assigned –movies[2] == null Using instance as target for method –movies[1].rating()

3 October 2002Web Technology for IE18 Mixing Creation and Elt Insertion public class Demonstrate { public static void main (String argv[]) { Movie movies[] = {new Movie(5,6,3), new Movie(8,7,7), new Movie(7,2,2), new Movie(7,5,5)}; int sum = 0; for (int counter=0; counter < movies.length; ++counter) { sum += movies[counter].rating(); } System.out.print("The average rating of the " + movies.length); System.out.println(" movies is " + sum / movies.length); }

3 October 2002Web Technology for IE19 Arrays and Memory Arrays are reference type variables Integer arrays contain a length variable and 4 bytes of memory per instance Class instance arrays contain a length variable and several bytes for the address of each instance

3 October 2002Web Technology for IE20 Higher Dimension Arrays You can easily define arrays of higher dimension –double 2DArray [] [] = new double[2][100];

3 October 2002Web Technology for IE21 Passing an Array to a Method To designate that a parameter is array –public static Movie[] readData(Movie movies []) throws IOExc.. –public static Movie[] readData(Movie[] movies) throws IOExc.. E.g.: put file-reads into Auxiliary Class Some ways to define readData: –Create array, pass array address to method, return address –Create array, pass array address to method, return nothing –Create array variable, pass filename to method, return array

3 October 2002Web Technology for IE22 Command-Line Arguments The main methods has one parameter –an array of Strings, argv[] –argv.length is # command-line arguments

3 October 2002Web Technology for IE23 Example public class Command { public static void main(String argv[]) { Movie m = new Movie(Integer.parseInt(argv[0]), Integer.parseInt(argv[1]), Integer.parseInt(argv[2])); System.out.println("The rating is " + m.rating()); }

3 October 2002Web Technology for IE24 Vectors Vectors vs. Arrays –variable in length –insertions can occur at any point –elements can only be class instances Provided by Java’s utility package –import java.util.* –Vector v = new Vector();

3 October 2002Web Technology for IE25 Vector Methods Insertions and deletions –v.addElement(m) … adds to back end of vector –v.insertElementAt(m,0) … adds to front of vector –v.removeElementAt(0) … removes first element –v.setElementAt(m,4) … replaces element Access to elements –v.firstElement() –v.lastElement() –v.elementAt(2) Size of Vector – v.size()

3 October 2002Web Technology for IE26 A Little Quiz Which methods do you need to represent FIFO queues? Which methods do you need to represent LIFO queues (stacks)?

3 October 2002Web Technology for IE27 Vectors as Targets All vector elements are instances of the Object class All vector methods work with instances of the Object class You can work with an element of the vector class by casting the element: –( (Movie) (v.firstElement()) ).rating()

3 October 2002Web Technology for IE28 Example import java.io.*; import java.util.*; public class Auxiliaries2 { public static Vector readData(String fileName) throws IOException { FileInputStream stream = new FileInputStream(fileName); InputStreamReader reader = new InputStreamReader(stream); StreamTokenizer tokens = new StreamTokenizer(reader); Vector v = new Vector(); while (tokens.nextToken() != tokens.TT_EOF) { int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; v.addElement(new Movie(x,y,z)); } stream.close(); return v; }}

3 October 2002Web Technology for IE29 Iterators An iterator maintains a pointer to a place on the parent vector To create an iterator –Iterator i = v.iterator() Some Iterator methods –i.next() … returns element, advances pointer –i.hasNext()

3 October 2002Web Technology for IE30 Example import java.io.*; import java.util.*; public class Demonstrate { public static void main(String argv[]) throws IOException { Vector mainVector = Auxiliaries2.readData("input.data"); int size = mainVector.size(); for ( Iterator i = mainVector.iterator(); i.hasNext(); ) { System.out.println(( (Movie) i.next() ).rating()); }

3 October 2002Web Technology for IE31 Working with Char & Strings What you can do with Strings Specifying delimiters in File-reads

3 October 2002Web Technology for IE32 The String s s.length() … compare this to arrays + concatenates two strings s.charAt(0) extracts first character s.charAt(0)==‘M’ … note single quotes switch(s) … use in switch statements char c = s.charAt(0); default character is ‘\u000’

3 October 2002Web Technology for IE33 Example (excerpt) while (tokens.nextToken() != tokens.TT_EOF) { String codeString = tokens.sval; tokens.nextToken(); int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; switch (codeString.charAt(0)) { case 'M': v.addElement(new Movie(x,y,z)); break; case 'S': v.addElement(new Symphony(x,y,z)); break; }

3 October 2002Web Technology for IE34 Specifying Delimiters To advise the tokens tokenizer to use double quotation marks to delimit strings: –tokens.quoteChar((int) ‘”’) To tell the tokenizer to recognize carriage returns: –tokens.eolIsSignificant(true);

3 October 2002Web Technology for IE35 Example (excerpt) tokens.quoteChar((int) '"'); tokens.eolIsSignificant(true); Vector v = new Vector(); while (tokens.nextToken() != tokens.TT_EOF) { String nameString = tokens.sval; tokens.nextToken(); int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; Movie m = new Movie(x,y,z); m.title = nameString; if (tokens.nextToken() == tokens.TT_EOL) {} else { m.poster = tokens.sval; tokens.nextToken(); } v.addElement(m); }

3 October 2002Web Technology for IE36 Working with O/p File Streams To connect to output file –FileOutputStream stream = new FileOutputStream(“output.data”); To write more than 1-byte-at-a-time –PrintWriter writer = new PrintWriter(stream); It’s good to flush out buffered characters –writer.flush() Close the file –stream.close()

3 October 2002Web Technology for IE37 Example (part) import java.io.*; import java.util.*; public class Demonstrate { public static void main(String argv[]) throws IOException { FileOutputStream stream = new FileOutputStream("output.data"); PrintWriter writer = new PrintWriter(stream); Vector mainVector = Auxiliaries4.readData("input3.data"); int size = mainVector.size(); for (Iterator i = mainVector.iterator(); i.hasNext();) { Movie m = (Movie) i.next(); m.writeToFile(writer); writer.println(m.rating()); } writer.flush(); stream.close(); System.out.println("File written"); }}