Colorado State University Logo | CS 163/4: Java Programming (CS 1) Colorado State University Logo | CS 163/4: Java Programming (CS 1)
CS 163/4: Java Programming (CS 1)
Computer Science

Lab 09 - CSVReader

Introduction

This lab will apply the concepts of objects and their creation, culminating in an object that will read Comma Seperated Value (CSV) files.

Review

Before beginning, a review of Scanners will help us!

Scanners will be heavily used in the creation of this CSVReader so it will be helpful to go over a couple of methods.

  • nextLine(), this method will read in an entire line within the CSV file. If it is assigned to a variable that line read in will then be stored in the variable, the lines read can also be empty.
  • hasNext() is a useful method that simply checks to see if there are more tokens or lines to read in from the Scanner.

Starting the lab!

The CSVReader will enable you to read a common file type known as CSV or Comma Separated Value, which is practically an excel file or spreadsheet format.

Header1 Header2 Header3
Cell content More content! Even more content!
Hey! A CSV, can look like this!

The only difference being that our values, instead of being seperated by lines, will be seperated by commas!

As a summary, this object should read in each row of data within a CSV file. We can accomplish this with the use of a Scanner and some extra methods!

Step 1

To begin the creation of a CSVReader for P3, create the instance variables that will be needed throughout the life of your CSVReader object.

This object will have 2 instance variables we must specify…

  • Deliminator, which should be a String set to a comma, “,”, for now as the values will be Comma Separated Values (CSV).
  • A Scanner, which will be used throughout the lifetime of our object to “Scan” our CSV file for lines/tokens. Do not assign the Scanner just yet.

Step 2

For step one we will be creating a constructor for our CSVReader.

Constructing a Constructor

Let’s make a constructor for this object! We will require 2 parameters for our constructor.

  • The name of the file which we are attempting to open, this can be provided as a string.
  • A boolean to note if we are to skip the header of the CSV file. The header is typically a grouping of labels for the columns of data below them.

By now, your constructor’s signature should look like this:

public CSVReader(String fileName, boolean skipHead)

After creating the constructor signature, we must actually work on the guts of the constructor. The code below and provided on zyBooks is a try-catch block. The try-catch being needed as creating a Scanner can sometimes go awry. We use the FileNotFoundException parameter within our catch block as it will “catch” that error, FileNotFoundException, if it occurs. All other errors will not be caught by our catch statement.

try {
    //Your code here.
}catch (FileNotFoundException io) {
    System.err.printf("File %s not found%n", file);
    System.exit(1);
}

Within the try block we want to create a File object using the fileName that must be provided as a parameter. The creation of this file object follows the typical syntax of Scanner, except we are using File in place of Scanner, don’t forget to change the parameter provided to our new File object!

File file = new File(filename); 

Note: The CSV file provided by fileName must be within the project directory, not the src directory while you are in an IDE such as IntelliJ, in zyBooks this will not matter. To avoid the need of having the CSV file in the same directory, try experimenting with having a file path as the fileName parameter.

The aforementioned File object is only to be used when we instantiate our instance variable Scanner. In place of where we would typically put “System.in”, replace it with your previously created File object. See if you can create the File object in this same space as a small challenge!

Now our constructor is nearly done! You may have noticed we have not used our skipHead parameter just yet. If our skipHead parameter provided is true, we just want to skip the first line of input, a simple call of .nextLine() is all that is needed in this case. In this case that skipHead if false, we do not need to do anything!

And with that, our constructor is completed! We only have two methods remaining, or one if you are a minimalist.

Testing

There is little you can test at this point as only the constructor has been created, but try to create CSVReader objects within your main method, providing skipHead as both True and False. For the fileName parameter, please use test.csv.

Step 3

hasNext()

The next step would be to create a helper method, hasNext() to use in the following function. This method will:

  • be accessible to everyone
  • need an instance of an object to be created in order to be called.
  • return a boolean type.
  • refer to our scanner to check if there is another line of input, or in other words has a next line of input.
    • Also check our scanner if it is null.
    • In the case that our Scanner has another line of input, and is not null, return true;
  • in the case that our Scanner is null, or we do not have another line of input, we shall return false.

The hasNext() function from Scanner will be useful within this method.

Testing

Using your previously created CSVReader object or objects, try to use .hasNext() upon it. The returning value should be a boolean, true or false depending on the presence of content in the CSV!

Step 4

getNext()

Our last method will be getNext(), this will be a function that we can call upon any CSVReader object to “scan” the next line of input.

This method will:

  • be accessible to everyone
  • need an instance of an object to be created in order to be called.
  • return a String[], or String array.
  • check if another line is available using the hasNext() method just created.
    • If there is another line of input, we should assign it to a String object using the Scanner’s nextLine() function. After storing the String, we should check if it is empty.
      • If the String returned by nextLine() is empty, we should return null, as there are no values to return.
      • If the String returned is not empty, we should split() the String into an array and the return that!.
    • If there is not another line of input, simply return null.

This method returns an array of Strings, so for each line of data returned we can index the array and see what data is contained. Such as if the array returned with length of 5, we can use returnedLine[4] to view the last piece of data, as the indexing begins at 0!

Testing

Now that our CSVReader is in it’s final stages, we should test it! Construct a while loop using hasNext() as the condition, within the while loop, assign a String[] to the getNext() function, so that the pointer on our Scanner is being moved. Once the String[] is stored, you can print the data or use it however you would like. An option to see the data would be to construct a for loop to print out each value, it should look something like the code below!

for(int i = 0; i < line.length; i++){
    System.out.print(line[i] + ',');
}

With our getNext() method the cases in which it returns null are useful, as we can check after our String[] has been assigned if it is equal to null, in the case that it is the continue keyword will come in handy!

Computer Science Department

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

CS 163/4: Java Programming (CS 1)

Computer Programming in Java: Topics include variables, assignment, expressions, operators, booleans, conditionals, characters and strings, control loops, arrays, objects and classes, file input/output, interfaces, recursion, inheritance, and sorting.