Last Time Reviewed method overloading. A few useful Java classes:

Slides:



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

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.
Today Quiz solutions are posted on the Grading page. Assignment 2 is posted. Due the first Friday after Reading Week. All about null Start File Input/Output.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
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.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
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 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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
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.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Winter 2006CISC121 - Prof. McLeod1 Last Time Wrapper classes JFileChooser (along with JOptionPane, and JColorChooser !) Text File Output.
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.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Managers and “mentors” identified on projects page. All member accounts created and projects populated.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 1 due Friday, 7pm. RAD due next Friday. Presentations week 6. Today: –More details on functions,
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a 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.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
Today Review passing by reference and pointers. null pointers. What is an Object? Winter 2016CMPE212 - Prof. McLeod1.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Today… StringTokenizer class. Method Overloading. Catching Exceptions (and what they are!). Start Pointers and Aliasing. Winter 2016CMPE212 - Prof. McLeod1.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
User-Written Functions
Chapter 7 User-Defined Methods.
Object Writing in files
Objectives You should be able to describe: Interactive Keyboard Input
Chapter 17 Binary I/O 1.
CISC/CMPE320 - Prof. McLeod
Fall 2017 CISC124 9/18/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
Java Programming: From Problem Analysis to Program Design, 4e
Exceptions and files Taken from notes by Dr. Neil Moore
Fall 2017 CISC124 9/21/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
MSIS 670: Object-Oriented Software Engineering
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
Chapter 2: Basic Elements of Java
Exceptions and files Taken from notes by Dr. Neil Moore
Fall 2018 CISC124 12/1/2018 CISC124 Note that the next assignment, on encapsulation, is due next Wednesday at 7pm – not Friday. The next Quiz is not until.
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Fall 2018 CISC124 2/15/2019 CISC124 TA names and s will be added to the course web site by the end of the week. Labs start next week in JEFF 155:
CISC124 Labs start this week in JEFF 155. Fall 2018
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Fall 2018 CISC124 2/22/2019 CISC124 Quiz 1 This Week. Topics and format of quiz in last Tuesday’s notes. The prof. (me!) will start grading the quiz.
CISC/CMPE320 - Prof. McLeod
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
CISC101 Reminders All assignments are now posted.
Winter 2019 CMPE212 4/7/2019 CMPE212 – Reminders
FINAL EXAM Final Exam Wednesday, Dec 14: 8: :00 AM (Frny G140)
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
CMPE212 – Reminders Course Web Site:
Last Time Some discussion of program “efficiency”. Arrays – 1D and 2D
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
Winter 2019 CMPE212 5/10/2019 CMPE212 – Reminders
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
CMPE212 – Reminders Assignment 2 due next Friday.
FINAL EXAM Final Exam Tuesday, May 3: 1:00 - 3:00 PM (Phys 112)
David Davenport Spring 2005
Presentation transcript:

Last Time Reviewed method overloading. A few useful Java classes: Other handy System class methods Wrapper classes String class StringTokenizer class Text File I/O Spring 2006 CISC101 - Prof. McLeod

Announcements Assn 3 posted. Final on June 14 or 15? Room TBA. Last lecture on June 8. Spring 2006 CISC101 - Prof. McLeod

Today The File class. (Leftover from last week.) Not on the final exam!: Binary File I/O Random Access File I/O Back to methods Passing parameters by value and by reference. Review class attributes. An exercise to review File I/O, look at passing by reference and the use of class attributes. Variable scope and lifetime. Spring 2006 CISC101 - Prof. McLeod

Text File I/O Sample Programs (We looked at these programs last week). TextFileIODemo.java Saves a file with text provided by the user and then opens the file again and displays the contents to the screen. TextFileIODemoWithChooser.java Same program as above except the use of the JFileChooser class is demonstrated as an alternate means of getting a filename from the user. Spring 2006 CISC101 - Prof. McLeod

Without using FileReader You can also send a File object to the Scanner class when you instantiate it instead of a FileReader object. You will still need to do this in a try catch block. See the second demo program. Spring 2006 CISC101 - Prof. McLeod

The File Class File is a class in the java.io.* package. It contains useful utility methods that will help prevent programs crashing from file errors. For example: File myFile = new File(“test.dat”); myFile.exists(); // returns true if file exists myFile.canRead(); // returns true if can read from file myFile.canWrite(); // returns true if can write to file Spring 2006 CISC101 - Prof. McLeod

The File Class, Cont. myFile.delete(); // deletes file and returns true if successful myFile.length(); // returns length of file in bytes myFile.getName(); // returns the name of file (like “test.dat”) myFile.getPath(); // returns path of file (like “C:\AlanStuff\JavaSource”) Spring 2006 CISC101 - Prof. McLeod

The File Class, Cont. All of these methods can be used without having to worry about try/catch blocks, which is nice! See the second demo program for a few examples of File class method use. Spring 2006 CISC101 - Prof. McLeod

Binary and Random Access Not on Final Exam! Binary files contain data exactly as it is stored in memory – you can’t read these files in Notepad! Text file is sequential access only. What does that mean? Random access can access any byte in the file at any time, in any order. Spring 2006 CISC101 - Prof. McLeod

Binary Files Binary files store “things” exactly as they are stored in memory, instead of converting them to ASCII characters. Cannot read the file in Notepad! More efficient use of file space. Faster. Can also store Objects, not just primitive types! You have to remember the file format from when you wrote the file - you cannot examine the file to “discover” the layout of the data. For example, if you wrote a long, you could read two int’s without getting an error (or the right values!) Spring 2006 CISC101 - Prof. McLeod

Binary File Output For Output, use ObjectOutputStream and FileOutputStream: ObjectOutputStream outputStream = new ObjectOutputStream (new FileOutputStream(fileName)); To append: ObjectOutputStream (new FileOutputStream(fileName, true)); Spring 2006 CISC101 - Prof. McLeod

Binary File Output – Cont. For example: ObjectOutputStream binFileOut = new ObjectOutputStream (new FileOutputStream(“data.dat”)); Spring 2006 CISC101 - Prof. McLeod

Binary File I/O – Output – Cont. Methods for Binary Output: binFileOut.writeInt(int); binFileOut.writeLong(long); binFileOut.writeDouble(double); binFileOut.writeFloat(float); binFileOut.writeChar(char); binFileOut.writeBoolean(boolean); binFileOut.writeUTF(String); Spring 2006 CISC101 - Prof. McLeod

Binary File I/O – Output – Cont. To close: binFileOut.close(); To flush: binFileOut.flush(); The flush() method immediately writes the file write buffer to the file, emptying the buffer. Normally the flush method is not needed unless you will not be closing the file for some time after the last write. Spring 2006 CISC101 - Prof. McLeod

Binary File I/O – Output – Cont. Delimiters (comma, space, tab, etc.) are not used between data values. CR/LF is not used. Data written to a binary file must be read back in exactly the same way it was written. For example if a sequence of data like: int, int, double, String is written to the file, it must be read back in exactly the same way into variables of matching types. Spring 2006 CISC101 - Prof. McLeod

Writing Objects An Object to be written to a file must implement the Serializable interface. (What the heck am I talking about!) Then use code like: binFileOut.writeObject(an_Object); An array is an Object, so an entire array can be written to a binary file with only one line of code! Spring 2006 CISC101 - Prof. McLeod

Binary File I/O - Input For Input, use ObjectInputStream and FileInputStream: ObjectInputStream InputStream = new ObjectInputStream (new FileInputStream(fileName)); For example: ObjectInputStream binFileIn = new ObjectInputStream (new FileInputStream(“data.dat”)); Spring 2006 CISC101 - Prof. McLeod

Binary File I/O – Input – Cont. Methods for Binary Input: binFileIn.readInt(); // returns int binFileIn.readLong(); // returns long binFileIn.readDouble(); // returns double binFileIn.readFloat(); // returns float binFileIn.readChar(); // returns char binFileIn.readBoolean(); // returns boolean binFileIn.readUTF(); // returns String binFileIn.readObject(); // returns an Object (you must cast it back to the original object type) Spring 2006 CISC101 - Prof. McLeod

Binary File I/O – Input – Cont. To close: binFileIn.close(); Spring 2006 CISC101 - Prof. McLeod

Binary File I/O – Input – Cont. If you know exactly how much data was written to a file, it is not necessary to detect when you are at the end. Otherwise, how to detect the end of a file? The normal file read operation cannot detect an EOF character. Use some end of file value (a primitive type) or String. But, the value(s) would have to follow the same data pattern as preceding data. Or catch EOFException. Spring 2006 CISC101 - Prof. McLeod

Other Binary File Classes You can use DataOutputStream and DataInputStream in place of ObjectOutputStream and ObjectInputStream, but the “Data…” classes cannot handle reading or writing Objects. Spring 2006 CISC101 - Prof. McLeod

Random File I/O Both text and binary file access is sequential only. Random access can access any byte in the file at any time, in any order. Used with large database files, for example. Spring 2006 CISC101 - Prof. McLeod

Random File I/O, Cont. Use the class RandomAccessFile, imported from the java.io package. (You will also need to import the classes IOException and FileNotFoundException, also in java.io.) Spring 2006 CISC101 - Prof. McLeod

Random File I/O, Cont. Create or open a binary file for reading and writing using: RandomAccessFile ioFile = new RandomAccessFile(“data.dat”, “rw”); Use ioFile.writeByte(byte_position) to write a byte at the provided location. Use ioFile.seek(byte_position) followed by ioFile.readByte() to read the byte at the location. Spring 2006 CISC101 - Prof. McLeod

Random File I/O, Cont. There are also similar methods to read and write all the other primitive types as well as String’s. You must read back the file just as you wrote it (just like normal binary file I/O). .length() gives you the size of the file in bytes. And, of course, .close() closes the file. These methods and the instantiation will have to be carried out with try/catch block(s). Spring 2006 CISC101 - Prof. McLeod

File I/O - Summary Use the File class to check the file before reading, and to get other useful info. If saving numeric data only, binary file operations are easiest. Delimiters are not required, and String parsing and String/number conversions are not needed. Files are sized more efficiently. If you do have to save “periodic” data in a text file, use a StringTokenizer (also built into the Scanner class) to break up (or “parse”) the large String’s. Spring 2006 CISC101 - Prof. McLeod

File I/O - Summary - Cont. Text file Output allows external editing of the file. (Use WordPad, not NotePad…) If your I/O operation is having problems locating the file, provide the full path to the file in your program. Remember to use "/" or "\\" in the path String. Remember to close() the file immediately after writing it. File I/O is slow!! Compared to data manipulation in RAM. Spring 2006 CISC101 - Prof. McLeod

File I/O - Summary - Cont. If you want to have binary file I/O, but wish to avoid sequential access or want to read and write to the same file at the same time, use Random File access. This is a little more work because you have to be concerned with your position within the file. Spring 2006 CISC101 - Prof. McLeod

Passing Values into a Method Parameters can be passed “by value” or “by reference”. Primitive types are passed by value, Objects are passed by reference. “Passing by reference” means that a memory address, or pointer, is passed into the method instead of a primitive type value. A variable that contains such a pointer can change the contents of the object outside the method. When a value is passed “by value” the method has no way of knowing anything about the variable that held the value and cannot change the contents of that variable outside the method. Spring 2006 CISC101 - Prof. McLeod

Passing Parameters into Methods 00990f int[] anArray 01110f This is what gets passed into a method: 01110f 3 34 12 19 2 -6 … These stay “put”: 0037ff int aVal2 571 Spring 2006 CISC101 - Prof. McLeod

Passing by Value or by Reference Note that an entire array is an object and is passed by reference, so the method can change the contents of the array. If an individual element of an array is a primitive type value, such a single element is passed by value. Spring 2006 CISC101 - Prof. McLeod

Exercise, Phase 1 – File I/O Review Download the file “Purchasing.java.txt” into your folder and remove the .txt extension (or just copy and paste the code into an empty program). Download the file “Inventory.txt” into the same folder. Open your java tool and have a look at both files. Spring 2006 CISC101 - Prof. McLeod

Exercise, Phase 1 – File I/O Review, Cont. You have an inventory of 20 items of various costs, as listed in the comma-delimited text file Inventory.txt. The Purchasing program obtains an order from the user, prompting for an item number between 0 and 19, and the number of these items to purchase. The total cost is calculated and the inventory is adjusted. Items to be “back-ordered” are left in the purchase order. You need to complete two methods in this class, countItems() and totalCost(). Spring 2006 CISC101 - Prof. McLeod

Exercise, Phase 1 – File I/O Review, Cont. Add a dummy return statement to totalCost(), so you can work on countItems() Complete the code for countItems() after you have read the comment for the method. Hint: use code in readInventoryAndCosts() to give you the file input syntax. Comment out code in the main method, so you can just test your countItems() method. Spring 2006 CISC101 - Prof. McLeod

Exercise, Phase 2 – Passing by Reference Examine the code in readInventoryAndCosts to see how this method is changing the contents of the arrays supplied as parameters. Complete the totalCost method. It is supplied, and must change the contents of three arrays supplied as parameters. How else could one method change the contents of three arrays? Spring 2006 CISC101 - Prof. McLeod

Passing by Value or by Reference, Summary So, passing a primitive type (int, double, float, long, etc.) is “passing by value” - the method does not change the original variable contents. String’s are passed like primitive types (they are “immutable” Objects). Arrays as passed by reference. The method can change the contents of the array. If individual array elements are primitive types, then a single element is passed by value. Re-declaration of an object (like an array) inside a method breaks the reference to the object - this is really bad form! Spring 2006 CISC101 - Prof. McLeod

Review - Class Attributes Variables that are declared at the same level as the methods are known as “class variables” or “class attributes” or “fields”. (Sometimes they are called “Global variables” - but they are not really global. Java does not allow the use of truly “Global” variables.) They must be declared to be “static” to be used by static methods (all our methods are static, for now). Otherwise declaration is exactly the same as declaring a variable inside a method: Spring 2006 CISC101 - Prof. McLeod

Class Variables - Cont. public class Conversions { // Perhaps these should also be final? public static double cmInInch = 2.54; public static double gramsInPound = 454; public static double convertInchesToCm (double val) { return val * cmInInch; } // end method // Other methods } // end class Spring 2006 CISC101 - Prof. McLeod

Class Variables - Cont. Class variables are known everywhere within a class - their “scope” is the entire class. The use of class variables is tempting, because it allows you to use a variable directly without passing it into a method. Only create a class variable if you find that most of your methods are passing this variable - otherwise don’t use them! (Why not?) Spring 2006 CISC101 - Prof. McLeod

Exercise, Phase 3 – Class Attributes Alter your Purchasing.java program so that the inventory and costPerItem arrays are declared as class attributes. Test your code to make sure it works the same. Since most methods use these two arrays, it makes sense to have them as class attributes. Which version of your program is easier to work with? Spring 2006 CISC101 - Prof. McLeod

Variable Scope A variable can be declared in five different places, all within a class, from innermost to outermost: Inside a block ({}), which is contained within a method. Inside a “for” statement. Inside a method, but not inside another block. Inside a parameter list. Inside a class, at the same “level” as the methods. A variable is not “known” outside its scope - it is as if the variable were not even declared. Spring 2006 CISC101 - Prof. McLeod

Variable Scope - Cont. Remember: That it is “wasteful” to declare a variable inside a loop. If a loop counter is declared in the for statement itself, it is not available outside the loop. If you try to access the value of a variable outside its scope, you will get an error. The same variable name cannot be used twice in the same scope. So you cannot declare the same variable name in an inner block, when it already exists in an outer block. The same variable name can be used in separate (not overlapping) scopes. - Be careful with this as it can cause confusion! Spring 2006 CISC101 - Prof. McLeod

Variable Lifetime Also called “duration”. When the execution of a program moves out of the scope of a non-static variable, it’s “lifetime” is over. In Java, it is “garbage collected” automatically. A static variable or method persists in memory after its first use and is not garbage collected until the program is complete. Only class attributes and methods can be called static. Spring 2006 CISC101 - Prof. McLeod