Download presentation
Presentation is loading. Please wait.
Published byBertha McKenzie Modified over 7 years ago
1
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
2
Announcements Assn 3 posted. Final on June 14 or 15? Room TBA.
Last lecture on June 8. Spring 2006 CISC101 - Prof. McLeod
3
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
4
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
5
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
6
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
7
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
8
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
9
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
10
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
11
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
12
Binary File Output – Cont.
For example: ObjectOutputStream binFileOut = new ObjectOutputStream (new FileOutputStream(“data.dat”)); Spring 2006 CISC101 - Prof. McLeod
13
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
14
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
15
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
16
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
17
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
18
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
19
Binary File I/O – Input – Cont.
To close: binFileIn.close(); Spring 2006 CISC101 - Prof. McLeod
20
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
21
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
22
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
23
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
24
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
25
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
26
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
27
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
28
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
29
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
30
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
31
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
32
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
33
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
34
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
35
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
36
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
37
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
38
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
39
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
40
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
41
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
42
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
43
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.