Download presentation
Presentation is loading. Please wait.
Published byMillicent Briggs Modified over 9 years ago
1
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System
2
Winter 2006CISC121 - Prof. McLeod2 Stuff… Assignment 1 is posted (finally!).
3
Winter 2006CISC121 - Prof. McLeod3 Today Wrapper classes JFileChooser Text File I/O The File class
4
Winter 2006CISC121 - Prof. McLeod4 Wrapper Classes Sometimes it is necessary for a primitive type value to be an Object, rather than just a primitive type. –Some data structures only store Objects. –Some Java methods only work on Objects. Wrapper classes also contain some useful constants and a few handy methods.
5
Winter 2006CISC121 - Prof. McLeod5 Wrapper Classes - Cont. Each primitive type has an associated wrapper class: Each wrapper class Object can hold the value that would normally be contained in the primitive type variable, but now has a number of useful static methods. charCharacter intInteger longLong floatFloat doubleDouble
6
Winter 2006CISC121 - Prof. McLeod6 Integer Wrapper Class - Example Integer number = new Integer(46);//”Wrapping” Integer num = new Integer(“908”); Integer.MAX_VALUE // gives maximum integer Integer.MIN_VALUE // gives minimum integer Integer.parseInt(“453”) // returns 453 Integer.toString(653) // returns “653” number.equals(num) // returns false int aNumber = number.intValue(); // aNumber is 46
7
Winter 2006CISC121 - Prof. McLeod7 Aside - Why an “ equals ” Method for Objects? The String class also has “ equals ” and “ equalsIgnoreCase ”. These wrapper classes also have an equals method. Why not use the simple boolean comparators ( ==, !=, etc.) with Objects? These comparators just compare memory addresses. How are you going to sort Objects?
8
Winter 2006CISC121 - Prof. McLeod8 Aside - Why an “ equals ” Method for Objects?, Cont. == can only compare memory addresses when Objects are compared. Most Data Container Objects will have both an equals method and a compareTo method. The equals method tests for equality using whatever you define as “equal”. The compareTo method returns a postive or negative int value (or zero to indicate “equal”), again depending on how you define one Object to be greater or less than another.
9
Winter 2006CISC121 - Prof. McLeod9 Wrapper Classes – Cont. The Double wrapper class has equivalent methods: Double.MAX_VALUE // gives maximum double value Double.MIN_VALUE // gives minimum double value Double.parseDouble(“0.45E-3”) // returns 0.45E-3 parseDouble is only available in Java 2 and newer versions. See the Java documentation for more on Wrapper classes.
10
Winter 2006CISC121 - Prof. McLeod10 Character Wrapper Class Many useful methods to work on characters: “ character ” is a char getNumericValue(character) isDigit(character) isLetter(character) isLowerCase(character) isUpperCase(character) toLowerCase(character) toUpperCase(character)
11
Winter 2006CISC121 - Prof. McLeod11 Built - In GUI Windows We will learn to build our own GUI windows, but you should be aware of the GUI Windows already built into Java: –JOptionPane –JColorChooser –JFileChooser These are all built to perform common tasks and are very easy to use. Imported from the javax.swing package. See “BuiltInDemo.java”.
12
Winter 2006CISC121 - Prof. McLeod12 JFileChooser A built in file browser/selector dialog box. The demo only used the chooser in the most simple way. For example, you can specify a starting folder and add as many file extension filters as you like. The chooser returns a File object, from which you can obtain much information about the file.
13
Winter 2006CISC121 - Prof. McLeod13 JFileChooser Window
14
Winter 2006CISC121 - Prof. McLeod14 JFileChooser Example Code (At the top : –import java.swing.JFileChooser; ) JFileChooser chooser = new JFileChooser(); int result = chooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) System.out.println(chooser.getSelectedFile());
15
Winter 2006CISC121 - Prof. McLeod15 JFileChooser, Cont. Upon completion of the dialog, the getSelectedFile() method returns a File object. This object can easily be used with file I/O code…
16
Winter 2006CISC121 - Prof. McLeod16 Simple Alternative Prompt the user for a filename as a String, using the console window.
17
Winter 2006CISC121 - Prof. McLeod17 File I/O Files provide a convenient way to store and re- store to memory larger amounts of data. We will use arrays to store the data in memory, and we’ll talk about these things later. Three kinds of file I/O to discuss: –Text –Binary –Random access For now, we’ll stick with text I/O.
18
Winter 2006CISC121 - Prof. McLeod18 Text File Output in Java 5.0 Use the PrintWriter class. (As usual), you must import the class: import java.io.PrintWriter; In your program: PrintWriter fileOut = new PrintWriter(outFilename); ( outFilename is a String filename we obtained somewhere else…)
19
Winter 2006CISC121 - Prof. McLeod19 Text File Output in Java 5.0, Cont. Unfortunately the instantiation of the PrintWriter object can cause a FileNotFoundException to be thrown and you must be ready to catch it: try { writeFile = new PrintWriter(outputFile); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(0); } // end try catch
20
Winter 2006CISC121 - Prof. McLeod20 Aside - File Paths in Strings Sometimes you might have to include a path in the filename, such as “C:\Alan\CISC212\Demo.txt” Don’t forget that if you have to include a “ \ ” in a String, use “ \\ ”, as in: “C:\\Alan\\CISC212\\Demo.txt”
21
Winter 2006CISC121 - Prof. McLeod21 Text File Output in Java 5.0, Cont. The PrintWriter constructor can also accept a File object (such as provided from JFileChooser !)
22
Winter 2006CISC121 - Prof. McLeod22 Text File Output in Java 5.0, Cont. The Object fileOut, owns a couple of familiar methods: print() and println(). When you are done writing, don’t forget to close the file with: fileOut.close(); Way easy!!
23
Winter 2006CISC121 - Prof. McLeod23 Text File Input in Java 5.0 Use the FileReader and Scanner classes. Our usual import statements: import java.util.Scanner; import java.io.FileReader; import java.io.FileNotFoundException; We’ll get to that last one in a minute.
24
Winter 2006CISC121 - Prof. McLeod24 Text File Input in Java 5.0, Cont. In my program: fileIn = new FileReader("Test.txt"); Scanner fileInput = new Scanner(fileIn); Scanner class’ constructor can also accept a File object directly. Unfortunately the FileReader constructor (what’s a “constructor” anyways?) throws a kind of exception that I cannot ignore - so the code above cannot be used exactly in this way.
25
Winter 2006CISC121 - Prof. McLeod25 Text File Input in Java 5.0, Cont. This works: FileReader fileIn = null; try{ fileIn = new FileReader("Test.txt"); } catch (FileNotFoundException e) { // Do something clever here! } Scanner fileInput = new Scanner(fileIn);
26
Winter 2006CISC121 - Prof. McLeod26 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 as shown in the previous slide. See the demo program “TextFileReaderDemo.java”
27
Winter 2006CISC121 - Prof. McLeod27 Text File Input in Java 5.0, Cont. We are going to have to talk about try/catch blocks soon! But for now, let’s get back to file input. To get the file contents, and print them to the console, for example: while (fileInput.hasNextLine()) { System.out.println(fileInput.nextLine()); }
28
Winter 2006CISC121 - Prof. McLeod28 Aside - Scanner Class’ Tokenizer The Scanner class has a built in String Tokenizer. Set the delimiters using the useDelimiter(delimiter_String) method. Obtain the tokens by calling the next() method. The hasNext() method will return false when there are no more tokens.
29
Winter 2006CISC121 - Prof. McLeod29 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 The File Class
30
Winter 2006CISC121 - Prof. McLeod30 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”)
31
Winter 2006CISC121 - Prof. McLeod31 Binary and Random Access 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. More about Binary and Random File Access later!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.