Java
Java

 

Introduction

CSV (Comma Separated Values) files are widely used to store and exchange data due to their simple structure. A CSV file contains rows of data where each row represents a record, and the values in each row are separated by commas. Parsing a CSV file allows us to extract and manipulate the data stored in it. In many cases, applications need to read and display the contents of a CSV file for further processing or analysis.

In this example, we will write a Java program to parse a CSV file and display its contents on the console. This involves reading the CSV file line by line, splitting the rows into individual values based on commas, and then displaying these values in a structured format.

Objective

The objective of this program is to demonstrate how to:

  • Read a CSV file using Java.
  • Parse each line of the CSV file and split the values by commas.
  • Display the parsed content in a human-readable format on the console.

Code

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CsvParser {
    public static void main(String[] args) {
        // Path to the CSV file
        String filePath = "data.csv";
        
        // Read and parse the CSV file
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            
            // Read each line from the CSV file
            while ((line = br.readLine()) != null) {
                // Split the line by commas
                String[] values = line.split(",");
                
                // Display the parsed values
                for (String value : values) {
                    System.out.print(value + " ");
                }
                System.out.println(); // Move to the next line
            }
        } catch (IOException e) {
            // Handle the exception
            System.err.println("Error reading the file: " + e.getMessage());
        }
    }
}

Program Explanation

This program works as follows:

  • The program uses a BufferedReader to read the contents of the CSV file line by line. The file path is provided as a string (in this case, data.csv).
  • For each line, the split method is used to break the line into individual values based on the comma delimiter. These values are stored in a string array values.
  • The values from each line are then printed to the console in a space-separated format. Each record is displayed on a new line.
  • If an error occurs while reading the file (for example, the file does not exist), an exception is caught and an error message is displayed.

How to Run the Program

To run this program, follow these steps:

  1. Save the program code in a file named CsvParser.java.
  2. Make sure you have a CSV file (for example, data.csv) in the same directory or provide the correct path to the CSV file.
  3. Compile the program using the Java compiler:
    javac CsvParser.java
  4. Run the compiled program:
    java CsvParser
  5. The contents of the CSV file will be printed to the console, with each value separated by a space.
© 2024 Learn Programming

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)