CSci 161 Lab #3
 

Code a Java class named Lab3 with a main() routine which will read a file using the read() method of the FileInputStream class. Recall that the read() method of a FileInputStream returns an integer between 0 and 255, representing the value of the byte it reads, and it returns a value of -1 when end-of-file is detected. Because this read() method can throw an IOException, you must either enclose your code in a try block followed by a catch block to catch an IOException, or else indicate that main() is throwing the IOException. If you decide to catch an IOException, you should probably just print an error message on the console and call the System.exit() method. As you read these bytes, dump their values on your console screen to give you confidence that your input code is working.

As you read the file contents, you are also to use an array of ByteCount objects (described below) to keep track of the number of times each different byte value has been seen. Perhaps there are some byte values that are more common than others in certain types of files. Text files, for instance, might have a lot of blank spaces and binary files might have a lot of zeros. You will be able to check out these conjectures by reading files of different types with your program.

Display your array of ByteCode objects in order by their byte values. Then sort them into decreasing order of frequency and print them out again. Try to make your output as readable as possible. If your output is voluminous, it may be better to redirect it to a text file so you can inspect it for correctness more easily. [Consider using the sort() method of the Arrays class to do your sorting.]

Your lab instructor will give you the names of one or more input files to process with your program. Your main routine, when activated, should receive a file name as a command line parameter.

Use this file as a starting point.

The description of a ByteCount object is:

   class ByteCount implements Comparable<ByteCount> {
      public int final charbyte;
      public int frequency;
      
      public ByteCount(int i) { 
         if (i >= 0 && i < 256 )  charbyte=i; else charbyte=0;
         frequency=0;
      }
      
     public int increment() {
        return ++frequency;
     }
     
     public int compareTo(ByteCount b) {
        if (this.frequency < b.frequency) return -1;
        else if (this.frequency > b.frequency) return 1;
        else return 0;
     }
     
     public String toString() {
        return "byte=" + ((Integer) charbyte).byteValue() + ":freq=" + frequency+"\t";
  }
  

 
When you are finished, ask your lab instructor to check your work and record your scores.