Reading a Delimited File

Introduction:

For separating a delimited file, we can use:

  • String class - has a split() method to identify the comma delimiter and split the row into fields.

  • Scanner class - has a useDelimiter() method to identify the comma delimiter and split the row into fields.

Objective:

In this Lab, we will demonstrate how to read a Delimited file by using Java. Below is one of the processes:

  • Create an object of type file. Set it to your file’s path, and then we will pass this file instance to the Scanner class for scanning. The Scanner class will read the file line-by-line.

  • Use the nextLine() method to read a line.

  • Split the file by delimiter by using String.split() method.

  • After the split, we can store data in ArrayList. We could store that line as a String[] array as shown below:

    ArrayList<String[]>
    
  • After that, for display, we can Iterate through Arraylist.

Learning Objective:

After this lab, learners will have demonstrated the ability to read a Delimited File using Java and using java methods.

Example 1

Click here to Download the Dummy file (Car.csv).

22KB
Open

Remember the path or location of the downloaded file. We will use that file in this Lab.

Create a class named ScanDelimiterdFile, or give any name to the class. Write the code below in that class.

💡 Note: Do not forget to change the path or location of the file (cars.csv) at line number 9.

The hasNext() method verifies whether the file has another line, and the nextLine() method reads and returns the next line in the file.

Example 2

Let’s make our code more professional using the concept of “Encapsulation.” Another way of handling a delimited file is by creating something called a Model, Pojo, or Entity. A Model is simply a class containing variables with getter() methods and setter() methods, corresponding to each column of the delimited file and containing everything a normal class can contain.

Assume that you have ‘course’ information in the form of a CSV file. As a developer, it is your responsibility to extract data from a file, and then display the data in a console. Finally, you import data into the database. This process is called ETL (Extract Transformation Load). Let’s see first how we can extract/read data from a CSV file in a professional way.

Click here - Download the Dummy file (CourseData.csv).

256B
Open

Create a class named course, and write the code below in that class. This will be our Model class.

If you notice, that class has only private variables, constructors, getters(), and setters() for each variable, so we can say it is Encapsulation.

Create a class named MyRunner. Write the below code.

💡Note: Do not forget to change the path or location of the file(CourseData.csv).

Output:

Last updated