COMMONS CSV (SANDBOX) framework reading and writing operation
Commons CSV is a Java library for reading and writing to CSV files.It uses a simple and easy -to -understand API to provide many flexible options, and users can easily process CSV data.
To use the Commons CSV framework for reading operations, we need to import related libraries first.The following is an example code:
import java.io.FileReader;
import java.io.IOException;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
public class CSVDataReader {
public static void main(String[] args) {
try {
CSVParser parser = new CSVParser(new FileReader("data.csv"), CSVFormat.DEFAULT.withHeader());
for (CSVRecord record : parser) {
String name = record.get("Name");
int age = Integer.parseInt(record.get("Age"));
String country = record.get("Country");
System.out.println("Name: " + name + ", Age: " + age + ", Country: " + country);
}
parser.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above code, we first created a CSVPARSER object. It uses FileReader to read the CSV file and specify the first act of the first behavior through the WithHeader () method of the CSVFormat class.Then, we traversed each line of the CSV file and used the record.get () method to obtain the value of each cell.
Next, let's take a look at how to use the Commons CSV framework for writing operations.The following is an example code:
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
public class CSVDataWriter {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("data.csv");
CSVPrinter printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Name", "Age", "Country"));
printer.printRecord("John Doe", 25, "USA");
printer.printRecord("Jane Smith", 30, "Canada");
printer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above code, we first created a CSVPrinter object. It uses FileWriter to write the CSV file and specify the name of the head line through the Withheader () method of the CSVFormat class.We then write each row of data into the CSV file with the Printer.printRecord () method.
It is very simple to read and write the use of the Commons CSV (Sandbox) framework. At the same time, it provides many flexible options so that developers can easily process CSV data.Whether it is processing a large amount of data or processing simple table data, the Commons CSV is a powerful choice.