0% found this document useful (0 votes)
9 views3 pages

Gmail - Read CSV

The document explains how to read CSV data in Java using three methods: BufferedReader for a simple built-in approach, Apache Commons CSV for more complex scenarios, and OpenCSV as an alternative library. Each method includes step-by-step instructions and code examples, highlighting the advantages of using libraries for better handling of CSV formats. The conclusion emphasizes choosing the appropriate method based on the complexity of the CSV data.

Uploaded by

Nagasai Maddula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views3 pages

Gmail - Read CSV

The document explains how to read CSV data in Java using three methods: BufferedReader for a simple built-in approach, Apache Commons CSV for more complex scenarios, and OpenCSV as an alternative library. Each method includes step-by-step instructions and code examples, highlighting the advantages of using libraries for better handling of CSV formats. The conclusion emphasizes choosing the appropriate method based on the complexity of the CSV data.

Uploaded by

Nagasai Maddula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Read CSV

1 message

Nagasai Maddula <[email protected]> Sun, 19 Jan, 2025 at 15:35


To: Nagasai Maddula <[email protected]>

Reading CSV data in Java can be done easily using various methods. One common approach is using Java's built-in libraries like
BufferedReader, but for more complex CSV reading, you can use Apache Commons CSV or OpenCSV. I'll explain both the basic built-in
method and a more advanced library-based approach for handling CSV files.

1. Using BufferedReader (Built-in Java)

Java’s BufferedReader allows you to read files line by line, and then you can use the split() method to separate data by commas.

Steps:

Open the CSV file using a BufferedReader.


Read each line and split the content by commas (or another delimiter if necessary).
Process the data accordingly.

Java Code Example (BufferedReader):

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

public class CSVReader {


public static void main(String[] args) {
String filePath = "path_to_your_csv_file.csv"; // Replace with your CSV file path

try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {


String line;
while ((line = br.readLine()) != null) {
// Split each line by comma (or use other delimiter)
String[] values = line.split(",");

// Process the data (printing in this case)


for (String value : values) {
System.out.print(value + "\t"); // Tab-separated values
}
System.out.println(); // Newline after each row
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation:

BufferedReader is used to read the file line by line.


split(",") is used to separate each line into values based on commas (CSV standard).
The for loop prints out each value, separated by tabs for clarity.

Output (For CSV Example):

If your CSV looks like this:

Name,Age,Country
John,25,USA
Alice,30,UK
Bob,22,Canada

The output would be:

John 25 USA
Alice 30 UK
Bob 22 Canada

2. Using Apache Commons CSV

Apache Commons CSV is a powerful library that can handle more complex scenarios, such as different delimiters, quoted fields, and more.
Steps:

Add the Apache Commons CSV dependency to your project.


Use CSVParser to read and parse the CSV file.

Maven Dependency (Apache Commons CSV):

If you are using Maven, add the following dependency to your pom.xml file:

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.10</version>
</dependency>

Java Code Example (Apache Commons CSV):

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class CSVReaderApache {


public static void main(String[] args) {
String filePath = "path_to_your_csv_file.csv"; // Replace with your CSV file path

try (Reader reader = new FileReader(filePath)) {


// Create a CSVParser
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader().withIgnoreHeaderCase().
withTrim());

// Iterate through CSV records


for (CSVRecord record : csvParser) {
String name = record.get("Name");
String age = record.get("Age");
String country = record.get("Country");

// Process the data (printing in this case)


System.out.println("Name: " + name + ", Age: " + age + ", Country: " + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation:

CSVParser reads the CSV file and parses it according to the provided format.
withHeader() allows the first row to be treated as headers, making it easier to refer to columns by name.
get("ColumnName") is used to retrieve data by column name (e.g., "Name", "Age", "Country").
The for loop iterates through the records and prints them.

Output (For CSV Example):

Name: John, Age: 25, Country: USA


Name: Alice, Age: 30, Country: UK
Name: Bob, Age: 22, Country: Canada

3. Using OpenCSV (Alternative Library)

OpenCSV is another library that is commonly used for CSV file reading and writing. It can handle various CSV formats and is easy to
integrate into your project.

Steps:

Add the OpenCSV dependency to your project.


Use CSVReader to read the file and parse the data.

Maven Dependency (OpenCSV):

<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.6</version>
</dependency>
Java Code Example (OpenCSV):

import com.opencsv.CSVReader;

import java.io.FileReader;
import java.io.IOException;
import java.util.List;

public class CSVReaderOpenCSV {


public static void main(String[] args) {
String filePath = "path_to_your_csv_file.csv"; // Replace with your CSV file path

try (CSVReader csvReader = new CSVReader(new FileReader(filePath))) {


List<String[]> records = csvReader.readAll();

// Iterate over the CSV records


for (String[] record : records) {
String name = record[0];
String age = record[1];
String country = record[2];

// Process the data (printing in this case)


System.out.println("Name: " + name + ", Age: " + age + ", Country: " + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation:

CSVReader.readAll() reads all records in the CSV file into a List<String[]>.


Each record is an array of strings (each value in a row), which can be accessed by index.

Output (For CSV Example):

Name: John, Age: 25, Country: USA


Name: Alice, Age: 30, Country: UK
Name: Bob, Age: 22, Country: Canada

Conclusion

BufferedReader is a simple, built-in method to read CSV data, but it lacks advanced features like handling quotes and commas
inside data.
Apache Commons CSV and OpenCSV are more sophisticated libraries, useful for handling more complex CSV formats, with better
parsing capabilities, handling of quotes, and customizable delimiters.

You can choose the method based on the complexity of the CSV data and whether you need a simple or more robust solution.

You might also like