The commonly used API of the OpenCSV framework
The OpenCSV framework is a Java library for processing the CSV (comma separation value) file.It provides a set of simple and easy -to -use APIs that can help us read data from CSV files and write data into CSV files.This article will introduce the commonly used APIs of the OpenCSV framework in detail, and provide Java code examples.
1. CSVReader class:
The CSVReader class is used to read the data of CSV files.It provides multiple structural functions, which can choose a suitable method to create objects as needed.The commonly used APIs of this class include:
-` Readnext () `: This method is used to read the data in the CSV file by line.It returns a String array that contains all the data of the current line.If the file has been read to the end, return null.
Example code:
CSVReader reader = new CSVReader(new FileReader("data.csv"));
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
// Data processing
}
reader.close();
2. CSVWriter class:
The CSVWriter class is used to write data into the CSV file.It provides multiple structural functions, which can choose a suitable method to create objects as needed.The commonly used APIs of this class include:
-`` writenext (string [] NextLine) `: This method is used to write a line of data of a String array into the CSV file.Each element in the array will be written into a cell in the file.
Example code:
CSVWriter writer = new CSVWriter(new FileWriter("data.csv"));
String[] data1 = {"John Doe", "30", "Male"};
writer.writeNext(data1);
String[] data2 = {"Jane Smith", "25", "Female"};
writer.writeNext(data2);
writer.close();
3. CSVPARSER class:
The CSVPARSER class is used to analyze the data in the CSV file.It provides multiple constructors for creating objects.The commonly used APIs of this class include:
-`Parseline (String Line)`: This method is used to analyze the given string, and return a String array, including parsing data.
Example code:
CSVParser parser = new CSVParser();
String line = "John Doe,30,Male";
String[] data = parser.parseLine(line);
4. CSVReaderBuilder and CSVWriterbuilder class:
The CSVReaderBuilder and CSVWriterBuilder class are used to create a builder of CSVReader and CSVWriter objects.They provide some optional configuration options to customize and write CSV files.
Example code:
CSVReader reader = new CSVReaderBuilder(new FileReader("data.csv"))
.withSkipLines(1)
.build();
CSVWriter writer = new CSVWriterBuilder(new FileWriter("data.csv"))
.withSeparator(';')
.build();
Through the above introduction, we understand the commonly used API of the OpenCSV framework.With these APIs, we can easily read and write data in the CSV file to achieve flexible processing and operation of CSV files.