CIS 26 EW6

 

DUE: Nov 16th, 2005

Goal:

  1. Learn how to do Text Formatting
  2. How to use the following classes String, String Tokenizer, StreamTokenizer, Array, Exception
  3. How to do File Input/Output

 

Specification:

A file tavel.txt contains information about the 20 sales persons of IBM. On each line is a last name, a first name, and the number of miles they travel each day roundtrip. You can use the StreamTokenizer or StringTokenizer class to read the file, process it, and create two new files. One file contains the lines sorted by name (first names are used if last names are identical). The other contains the lines sorted by miles. Be sure to throw appropriate exceptions.

 

[NOTE: Please check under helpful links and Notes BEFORE you make an attempt write the above programs. Don’t forget to import the appropriate packages (i.e java.io.* or java.util.* etc)]

]

Helpful Links and Notes:

 

1. Links to the

a. java input output tutorial

        i. java io slides that we have used during class lectures.

        ii. Tutorial from sun website

            http://java.sun.com/docs/books/tutorial/essential/io/index.html

b. Exception Tutorial

       i. java exception slides that we have used during class lectures.

       ii. Tutorial from SUN website which has a good explanations for advantages of Exception handling. 

           http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

c. Sorting Hints

       You can fairly write simple code to sort your data or you can use one the sort methods provided by Array package or other packages.

d. Notes on StreamTokenizer and examples using StringTokenizer

2. Link to the java io package summary

http://java.sun.com/j2se/1.4.2/docs/api/java/io/package-summary.html

 

3. Link to the slides that have used during class lectures for Input/Output, Exception handlings and other topics can be found here:

            http://www.cs.armstrong.edu/liang/introjb4/slide/slide.htm

   This site has other helpful links and quizzes.

            http://www.cs.armstrong.edu/liang/introjb4.html

 

4. Please remember to look up the JAVA APIs whenever you have confusion. No one expects any of us to remember all the methods and classes. More you use them, more you remember them. But the key idea is to understand the JAVA API specification and know how to use them!

 

Here is the description of couple of methods that came up during our last class discussion on going through java io slides.

 

a. public abstract void flush()

                    throws IOException

 

    Flush the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.

 

    Throws:

        IOException - If an I/O error occurs

 

NOTE: Using flush() method makes sure that all the stuff supposed to be written has been written in the intended destination.

 

b. read

 

public int read()

         throws IOException

 

    Read a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached. Subclasses that intend to support efficient single-character input should override this method.

 

    Returns:

        The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached

    Throws:

        IOException - If an I/O error occurs

 

NOTE: Apparently, read behaves the same way that we have guessed during our lectures. It reads a single character as its ASCII value.

 

4. write

 

public void write(int c)

           throws IOException

 

    Write a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.

 

    Subclasses that intend to support efficient single-character output should override this method.

 

    Parameters:

        c - int specifying a character to be written.

    Throws:

        IOException - If an I/O error occurs

 

NOTE: Apparently, write takes the ascii value of the character and write!

 

 

Notes on StreamTokenizer Class:

A BufferedReader object can read a whole line. Often, it is advantageous to read individual

components (tokens) in a line, one at a time, rather than read an entire line. In C++, the <<

operator does precisely that and also skips white space.

Java’s StreamTokenizer class facilitates the reading of individual tokens.

The constructor for StreamTokenizer object is

StreamTokenizer(Reader in)

The StreamTokenizer class provides the following static constants:

TT_WORD The token is a word.

TT_NUMBER The token is a number.

TT_EOL The end of line has been read.

TT_EOF The end of file has been read.

and variables

int ttype Contains the current token type (TT_WORD,TT_NUMBER etc)).

double nval Contains the value of the current token if the token is a number.

String sval Contains the current token if it is a word.

The method

nextToken()

returns the type of the next token (TT_WORD, TT_NUMBER,TT_EOL or TT_EOF). The

returned constant is available in the instance variable ttype and, if the token is a number or

string, its value is stored in either nval or sval.

Example:

Each line of a file contains a name and four grades. The program uses the StreamTokenizer

class to read the name and the grades. Output of the name and the average grade goes to a

second file.

import java.io.*;

import java.util.*;

public class Grades

{

private FileReader input;

private FileWriter output;

private StreamTokenizer in;

PrintWriter out;

public Grades()

{

try

{

input = new FileReader(new File("InputData.txt"));

output = new FileWriter(new File("OutputData.txt"));

in = new StreamTokenizer(input);// wrap FileReader

out = new PrintWriter(output); //wrap FileWriter

}

catch(IOException e)

{

System.out.println(e.getMessage());

System.exit(0);

}

}

public void processGrades()

{

String name;

int grade;

int sum = 0;

try

{

in.nextToken(); // get the next token

while ( in.ttype != StreamTokenizer.TT_EOF)

{

sum = 0;

// make sure the token is a word (name)

if (in.ttype == StreamTokenizer.TT_WORD)

name = in.sval;

else

throw new Exception("Improper format: name");

 

for (int i = 1; i <=4; i++) //read the four grades

{

in.nextToken();

// make sure the token is numeric

if (in.ttype == StreamTokenizer.TT_NUMBER)

sum = sum + (int)in.nval;

else

throw new Exception("Expecting Number");

}

out.println(name + ": " + (sum/4.0) );

in.nextToken();

}

input.close();

output.close();

}

catch (IOException e)

{

System.out.println("IOException " + e.getMessage());

}

catch (Exception e)

{

System.out.println(e.getMessage());

System.exit(0);

}

}

public static void main(String args[])

{

Grades gradeObject = new Grades();

gradeObject.processGrades();

}

}

 

The IO structure:

Example of using StringTokenizer Class:

//  Read scores from a text file and use

// StringTokenizer to extract numbers from the string

import java.io.*;

import java.util.StringTokenizer;

 

public class FileExtract

{

  public static void main(String args[])

  {

    double sum = 0;

 

    try

    {

      // Create file input stream

      BufferedReader in = new BufferedReader(

        new FileReader("filename"));

 

      String line;

 

      while ((line = in.readLine()) != null)

      {

        StringTokenizer st = new StringTokenizer(line);

 

        while (st.hasMoreTokens())

        {

          sum += Double.parseDouble(st.nextToken());

        }

      }

 

      // Display result

      System.out.println("The sum is " + sum);

    }

    catch (IOException ex)

    {

      System.out.println(ex);

    }

  }

}