Use Apache Commons CSV to implement the CSV file read and write operation in the Java class library
Apache Commons CSV is an open source Java class library. It provides a simple and flexible API to read and write CSV (comma segments) files.CSV files are a common text file format that is usually used to exchange data between different applications.
Before using Apache Commons CSV, we need to add it to our project first.It can be achieved by adding the following dependencies to the pom.xml file of the project:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.8</version>
</dependency>
Let's take a look at how to read and write the CSV file with Apache Commons CSV.
Read the CSV file:
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;
public class CSVReaderExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("data.csv");
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
for (CSVRecord record : parser) {
String name = record.get("Name");
String age = record.get("Age");
String city = record.get("City");
System.out.println("Name: " + name + ", Age: " + age + ", City: " + city);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above example, we use CSVFormat.default and withfirstResheader () to set the format of the CSV parser.By setting the first record as the head, we can use the column name to get the corresponding value.
Write to CSV file:
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.FileWriter;
import java.io.IOException;
public class CSVWriterExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("data.csv");
CSVPrinter printer = CSVFormat.DEFAULT.withHeader("Name", "Age", "City").print(writer);
printer.printRecord("John Doe", "30", "New York");
printer.printRecord("Jane Smith", "25", "London");
printer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above example, we use csvformat.default.withheader () to set the format and column title of the CSV printer.Then, we write the data into the CSV file in the form of recording through the Printer.printRecord () method.
In this way, we can easily use the Apache Commons CSV to implement the CSV file read and write operation in the Java class library.