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 arrayvalues
. - 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:
- Save the program code in a file named
CsvParser.java
. - Make sure you have a CSV file (for example,
data.csv
) in the same directory or provide the correct path to the CSV file. - Compile the program using the Java compiler:
javac CsvParser.java
- Run the compiled program:
java CsvParser
- The contents of the CSV file will be printed to the console, with each value separated by a space.