Class Notes - October 28
First off, we figured out what was wrong with the FileWriter. When using the FileWriter, you have to close the PrintWriter using pw.close(). We'll discuss this below...
Today we will focus on the StringTokenizer. This is an essential Java tool you will use frequently in your future programming. If you continue on to ICS 211 and 311, you will most likely get some sort of assignment (after our Project 2) that will require you to use this.
Topics for today:
Alternative File Reader / Writer: FileReader and FileWriter
Code Example: NewFile.java (fixed)
Last Thursday's Way: New way using File Reader / File Writer:
Using FileInputStream: File f =
new File("file.txt"); br.readLine will read a line of the file |
FileReader:
File f = new File("file.txt");
|
Using FileOutputStream: File fout = new
File ("outputFile.txt");
|
FileWriter: File fout = new
File ("outputFile.txt"); pw.println() will write a line of output to the file
// at the end of your
program, do this to write the file |
What is it?
It is a way to read a String, and break it up into pieces.
Why would we want to use it?
Say we want to store data for a program. We would probably make a data file. In that file, we can store data for different sets of data. For instance, for project 2, we would probably have a taxpayer per line in our data file. Therefore, each individual will have all of their data on one line of the file. We can separate the data by using a special character, such as a colon (":") that hopefully the user will not type as part of their input.
For example, in project 2, we need to store the taxpayer's name, income, and dependants. Our data file might look like this:
Frank:15000:0
Joe Schmoe:54000:2
Julie:12000:1
Toni Schmoni:36000:4
In this case, data is in the form of (Name : Income : # Dependants).
Using the String Tokenizer, we can separate on ":" to pull the pieces apart and
get the data back out.
Note: If the user was to type in "Mary Ja:ne"
for their name, this would mess up the String Tokenizer if we separate based on
a ":"
How it works:
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
System.out.println("Number of Tokens Left: " + st.countTokens());
}
String Tokenizer Methods:
As shown above, the most common methods used on a String Tokenizer are:
Code Examples:
StringTok1.java (simple String Tokenizer, separate w/ spaces)
StringTok2.java (simple String Tokenizer, separate w/ colon)
StringTok3.java (using a String Tokenizer to
read tokens from lines of a file) using input.txt
http://www2.hawaii.edu/~tp_200/ics111/fall2004/project2.html
- You'll use the StringTokenizer and the file readers / writers, plus lots of concepts from earlier in the class