Gmail - Read CSV
Gmail - Read CSV
1 message
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.
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:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Explanation:
Name,Age,Country
John,25,USA
Alice,30,UK
Bob,22,Canada
John 25 USA
Alice 30 UK
Bob 22 Canada
Apache Commons CSV is a powerful library that can handle more complex scenarios, such as different delimiters, quoted fields, and more.
Steps:
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>
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;
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.
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:
<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;
Explanation:
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.