Practical Guide: Learn the Apache Commons CSV framework technology in the Java class library
Practical Guide: Learn the Apache Commons CSV framework technology in the Java class library
Apache Commons CSV is an open source Java class library that provides the function of processing CSV files.CSV files are a file format that stores data in a pure text form, which is commonly used in data exchange and storage.
This article will introduce how to read and write the CSV file with Apache Commons CSV framework, and provide the corresponding Java code example.
1. Install Apache Commons CSV
First, the Apache Commons CSV library needs to be introduced in the Java project.You can import library files by Maven or manually downloading jar files.The following is an example of Maven dependent configuration:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.9</version>
</dependency>
2. Read the CSV file
Using Apache Commons CSV can easily read data in the CSV file.The following example code demonstrates how to read the CSV file with this framework and store the data in a two -dimensional array:
import org.apache.commons.csv.*;
public class CSVReaderExample {
public static void main(String[] args) throws Exception {
CSVParser csvParser = CSVParser.parse(new File("data.csv"), StandardCharsets.UTF_8, CSVFormat.DEFAULT);
for (CSVRecord record : csvParser) {
for (String value : record) {
System.out.print(value + " ");
}
System.out.println();
}
csvParser.close();
}
}
In the above example, we use the method of `csvparser.parse () to analyze the CSV file.Through cycles traversing the CSVRecord object, you can read the data in the file one by one and print the values of each line.
3. Write into CSV files
Using Apache Commons CSV can also easily write data into the CSV file.The following example code demonstrates how to use the framework to store the data in the CSV file:
import org.apache.commons.csv.*;
public class CSVWriterExample {
public static void main(String[] args) throws Exception {
FileWriter fileWriter = new FileWriter("output.csv");
CSVPrinter csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT);
csvPrinter.printRecord("Name", "Age", "City");
csvPrinter.printRecord("John Doe", 30, "New York");
csvPrinter.printRecord("Jane Smith", 25, "Chicago");
csvPrinter.close();
}
}
In the above example, we use the `CSVPrinter` object to write the data into the CSV file.First, we create an object of `Filewriter` and specify the name of the output file.Then, we use the method of `csvprinter.printoldRecord () to write the data into the file.
Summarize:
This article introduces how to read and write the CSV file with Apache Commons CSV framework.By using this framework, we can easily process data in the CSV file.By reading this article and refer to the Java code example provided, you can quickly get started and apply Apache Commons CSV framework in your project to process CSV files.