Colorado State University Logo | CS 150: Culture and Coding (AUCC 3B/GT-AH3) Colorado State University Logo | CS 150: Culture and Coding (AUCC 3B/GT-AH3)
CS 150: Culture and Coding (AUCC 3B/GT-AH3)
Computer Science

Lab 19 - History of Computer Science, A File IO Lab

The purpose of this lab is to help you in your Practical Project. Several of these methods and concepts will aid in the success of performing your own data anaylsis. In this lab, you will read in a file, process it’s data and write out the statistics to a new file.

What You will Learn

  • Creating/Using a separate class to read a file
  • Collecting data and storing it into an Array
  • Writing to a file

Step 0 - Getting Starting

In this program, we have two classes, FileIO.java and FileReader.java. FileIO.java will be our “driver” program or the main program that will bring the file reading and analysis together. FileReader.java will create the methods we use in FileIO.java to simply read in our file.

Main in FileIO

For this lab, main() is provided for you in FileIO.java and contains two method calls. One line calls readFile() in the FileIO class with the name of the input file "brief\_history\_of\_cs.txt". This method then calls other methods in both the FileIO and FileReader classes. The next line calls writeFileStats() with the name of the output file "output.txt". The method writes data to the output file in a certain format and uses values from the FileIO class array fileStats.

Here’s a sneak peak at what "brief\_history\_of\_cs.txt" contains…

A Brief History of Computer Science - World Science Festival

2700-2300 B.C. The Sumerian Abacus first appeared.
87 B.C. The Antikythera mechanism, the earliest known analog computer is developed in ancient Greece.
1703 A.D. German mathematician Gottfried Wilhelm Liebnitz introduces the binary number system.
1837 Charles Babbage invents the Analytical Engine.
1843 Ada Lovelace develops the first computer algorithm.
1936 Alan Turing invents the Turing Machine.
1941 Konrad Zuse invents Z3, the first programmable digital computer.
1947 The transistor is invented at Bell Labs.
...

Uncomment the provided lines after readFile() and writeFileStats() have been written.

FileReader.java

We will first need to read in our file before we perform any analysis, so let’s start with the methods in FileReader.java. The method signatures in the FileReader class are written for you. The purpose of the class is to process a file. We have one class variable that is a Scanner object called fileScanner which we will use to read the file.

Step 1 - beginScanning()

This method will initialize our class scanner fileScanner to read from the file we were given.

Try-catch

To do this, you will want to write a try-catch block with the catch just Exception e (you may want to google this to see how to use a try-catch if you are unfamiliar).

File and Scanner

Inside this try-catch block, you will want to create a file object with the fileName as your parameter. You will then want to use this file variable for your scanner. To do this, assign fileScanner to a new scanner with the file variable that you just create as the parameter of the scanner.

Below is an example of how you can create a file and a scanner to read that file…

// Creating File instance to reference text file
File text = new File("C:/temp/test.txt");
// Creating Scanner instance to read File
Scanner scnr = new Scanner(text);

Throwing out irrelevant data

After you have initialized your class variable fileScanner in your try catch, you will need to immediately “throw out” the first line of the file. The first line of the file is just a header that is the title of the file, A Brief History of Computer Science - World Science Festival. We throw it out because it doesn’t actually hold any data for our statistical analysis.

To “throw out” the first line of the file, you will just need to simply read the next line of the scanner. Don’t store it in any variable, just call .nextLine().

Step 1 - hasMoreLines()

This method will simply check to see if there is more to read from the file.

To do this, we will check to see if our class scanner is not equal to null and can still read the next line. If this is true, then we will return true, otherwise false we will just return false.

Hint: use the scanner method .hasNextLine()

Step 2 - getNextLine()

The method will simply return the next line of the file as a string.

To do this, you will use your class scanner variable fileScanner and use the appropriate scanner method to get the next line in the file.

FileIO.java

Now that we’ve finished implementing those methods in FileReader.java, let’s switch over to FileIO.java

Step 3 - determineFileLineStats()

The purpose of this method is to analyze one line from the file and increment the appropriate elements of the int array (a class variable) called fileStats that holds the stats of the file.

The stats of this file we are collecting are the number of occurrences of these characters: '0', '1', 'u', 'z'/'Z'. Our int array fileStats holds the number of occurrences of these characters. fileStats at index 0 holds the number of 0’s (zeros), fileStats at index 1 the number of 1’s (ones), fileStats at index 2 holds the number of lowercase u’s and fileStats at index 3 holds the number of upper and lowercase z’s

Method signature of determineFileLineStats()

First, write the method signature. The method determineFileLineStats() is a static method that does not return anything. It takes in a String as a parameter that represents a line from the provided file.

Extracting data from one line

To collect the data from the line write a loop to iterate over each character from the line given. In the loop, use a switch statement to determine the following:

  • If the current character is a zero, increment the first element of the fileStats array.
  • If the current character is a one, increment the value of the second element of fileStats.
  • If the current character is a lowercase u, increment the value of the third element of fileStats.
  • And if the current character is a lowercase z or an uppercase Z, increment the value of the fourth element of fileStats.

Step 4 - readFile()

The purpose of this method is to read the file. Once we start reading the file we will process the file while there are still lines to read. With each line of the file, it will extract the data and increment the appropriate stats.

Method signature of readFile()

The method readFile() is a static method that does not return anything. It takes in a String as a parameter that represents the name of the file.

Start reading

In this method we will use the methods from FileReader.java to start the scanning process ( beginScanning()), to check if there are more lines to read ( hasMoreLines()) and to get the next line of the file ( getNextLine() \). To use these methods, you have to type the name of the class ( FileReader), dot (.), and then the method (how you would normally call it). For example, If I wanted to open and a initialize a scanner to a file called "idkwhattocallthis.txt", the syntax would be…

FileReader.beginScanning("idkwhattocallthisfile.txt"); 

The first step we will do in our method readFile() will be to open the file and create a scanner to read the file. Use the method from our FileReader.java to do this is one step. Hint: You won’t need to create a new File object since the method in FileReader.java does that for you.

Read each line

Then, we will need to read through each line of the file. To do this, create a while loop that will continue to repeat while there are still more lines to read. Use the method from our FileReader.java to determine if there are more lines to read.

Process each line

For each iteration of the while loop we will want to get the next line from the file and then process its data. To do so, use the method from FileReader.java to get the line from the file as a string. Then immediately pass that line into the method determineFileLineStats() to extract the data from each line.

Step 5 - writeFileStats()

This last method we will write will open a new file to write out the stats of the file (ex. "output.txt"). We will practice using PrintWriter and File. This method will not use any methods from FileStats.java because at this point we have read everything in from the other file (ex. "brief\_history\_of\_cs.txt") and stored the data in the int array fileStats.

Method signature of writeFileStats()

The method writeFileStats() is a static method that does not return anything. It takes in a string as a parameter that represents the name of the file.

Try-catch

Write a try-catch block in order to create a File object in the next step. Do this like you did in FileReader.java. We do this just in case there’s any issues opening the file, it will stop the program instead of crashing.

Create a File and PrintWriter

Inside this try-catch we need to first create a new File variable with the string parameter given to us. This will be very similar to creating a File in our beginScanning() method. Once we’ve created the file we need to create a PrintWriter. A PrintWriter is how we write to a file, it is created like a Scanner and used like System.out when printing/writing to a file. Here’s an example of PrintWriter to help if you get stuck!

Hint: I always accidentally write PrinterWriter instead of PrintWriter so be sure to not make my mistake.

PrintWriter printWriter = new PrintWriter(file);
printWriter.println("Look at me! I'm writing to a file!");

Write to the file

In the output file, first write the participation statement:

I participated in today's lab and my program writes to the output file.

Write the statistics of the input file to the output file. Utilize the following prompts before the respective value:

Number of zeros:

Number of ones:

Number of u's:

Number of z/Z's:

Close the PrintWriter

Your last step is to close the PrintWriter. If we don’t close our PrintWriter Java doesn’t know that we are done adding to the file and it will never actually get written to the file. PrintWriter collects everything you want to write and then once you’ve closed it, it will write everything to the file at once.

Computer Science Department

279 Computer Science Building
1100 Centre Avenue
Fort Collins, CO 80523
Phone: (970) 491-5792
Fax: (970) 491-2466

CS 150: Culture and Coding (AUCC 3B/GT-AH3)

Survey of computer science, formal logic, and computational thinking. Explores the historical, gender, and cultural perspectives on the role of technology in society. Includes learning a basic programming language. Students will be expected to write small programs, and construct written arguments on ways in which technology influences our modern culture. Previous computer science experience not necessary.