Introduction to Commons CSV (SANDBOX) framework
Introduction to Commons CSV (SANDBOX) framework
Commons CSV (SANDBOX) is a Java library used to read and write to the CSV (comma segmental value) file.CSV file is a common text format for representing table data.Commons CSV provides a simple and flexible way to handle this file format.
The Commons CSV library provides a set of APIs that can easily read and write CSV files.It supports analysis based on various separators such as commas, segmentation, and formula, and provides many configuration options to adapt to different CSV file formats.
Below is a Java code example using the Commons CSV library:
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) {
String csvFile = "data.csv";
try (CSVParser parser = new CSVParser(new FileReader(csvFile), CSVFormat.DEFAULT)) {
for (CSVRecord record : parser) {
String name = record.get(0);
String age = record.get(1);
String city = record.get(2);
System.out.println("Name: " + name + ", Age: " + age + ", City: " + city);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The above code reads the data from the CSV file called "Data.csv" by using the `csvparser` class and the` csvformat` class.For each line of records, we use the `Get ()` method to get the value of each field and print it out.
In addition to reading CSV files, Commons CSV also provides the function of writing CSV files.The following is a simple example:
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
public class CSVWriterExample {
public static void main(String[] args) {
String csvFile = "data.csv";
try (CSVPrinter printer = new CSVPrinter(new FileWriter(csvFile), CSVFormat.DEFAULT)) {
printer.printRecord("John Doe", "25", "New York");
printer.printRecord("Jane Smith", "30", "London");
} catch (IOException e) {
e.printStackTrace();
}
}
}
The above code creates a CSV file called "Data.csv", and uses the `csvprinter` class to write the record file.In this example, we use the `PrintRecord ()` method to write each line to the file.
Commons CSV provides a simple and flexible solution for reading and writing of CSV files, which is very useful when processing table data.By provided API, we can easily read and write CSV files and configure them as needed.Regardless of the analysis of existing CSV files or generating new CSV files, COMMONS CSV is a reliable choice.