Transcript ppt
Last Time
• Misc. useful classes in Java:
– String
– StringTokenizer
– Math
– System
Winter 2006
CISC121 - Prof. McLeod
1
Stuff…
• Assignment 1 is posted (finally!).
Winter 2006
CISC121 - Prof. McLeod
2
Today
• Wrapper classes
• JFileChooser
• Text File I/O
• The File class
Winter 2006
CISC121 - Prof. McLeod
3
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.
Winter 2006
CISC121 - Prof. McLeod
4
Wrapper Classes - Cont.
• Each primitive type has an associated wrapper class:
char
int
long
float
double
Character
Integer
Long
Float
Double
• 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.
Winter 2006
CISC121 - Prof. McLeod
5
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
Winter 2006
CISC121 - Prof. McLeod
6
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?
Winter 2006
CISC121 - Prof. McLeod
7
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.
Winter 2006
CISC121 - Prof. McLeod
8
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.
Winter 2006
CISC121 - Prof. McLeod
9
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)
Winter 2006
CISC121 - Prof. McLeod
10
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”.
Winter 2006
CISC121 - Prof. McLeod
11
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.
Winter 2006
CISC121 - Prof. McLeod
12
JFileChooser Window
Winter 2006
CISC121 - Prof. McLeod
13
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());
Winter 2006
CISC121 - Prof. McLeod
14
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…
Winter 2006
CISC121 - Prof. McLeod
15
Simple Alternative
• Prompt the user for a filename as a String,
using the console window.
Winter 2006
CISC121 - Prof. McLeod
16
File I/O
• Files provide a convenient way to store and restore 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.
Winter 2006
CISC121 - Prof. McLeod
17
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…)
Winter 2006
CISC121 - Prof. McLeod
18
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
Winter 2006
CISC121 - Prof. McLeod
19
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”
Winter 2006
CISC121 - Prof. McLeod
20
Text File Output in Java 5.0, Cont.
• The PrintWriter constructor can also accept a
File object (such as provided from
JFileChooser!)
Winter 2006
CISC121 - Prof. McLeod
21
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!!
Winter 2006
CISC121 - Prof. McLeod
22
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.
Winter 2006
CISC121 - Prof. McLeod
23
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.
Winter 2006
CISC121 - Prof. McLeod
24
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);
Winter 2006
CISC121 - Prof. McLeod
25
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”
Winter 2006
CISC121 - Prof. McLeod
26
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());
}
Winter 2006
CISC121 - Prof. McLeod
27
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.
Winter 2006
CISC121 - Prof. McLeod
28
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
Winter 2006
CISC121 - Prof. McLeod
29
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”)
Winter 2006
CISC121 - Prof. McLeod
30
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!
Winter 2006
CISC121 - Prof. McLeod
31