Use OpenCSV framework to implement the introduction and export of CSV files

Use OpenCSV framework to implement the introduction and export of CSV files CSV (comma separation value) is a commonly used file format for storing and transmission table data. It uses commas as a separatist symbol between fields.OpenCSV is an easy -to -use Java framework that is used to read and write CSV files. Import CSV file To introduce CSV files, first of all, the dependencies of OpenCSV need to be added and imported the required classes. import com.opencsv.CSVReader; import java.io.FileReader; import java.io.IOException; public class CSVImportExample { public static void main(String[] args) { CSVReader reader = null; try { reader = new CSVReader(new FileReader("data.csv")); String[] nextLine; while ((nextLine = reader.readNext()) != null) { // Process each line of data for (int i = 0; i < nextLine.length; i++) { System.out.print(nextLine[i] + " "); } System.out.println(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } } In the above code, we first created a CSVReader object to read a CSV file named "Data.csv".Then, we read files with the readnext () method row to store the data of each line in a string array.Next, we can process the data of each line, such as printing output. Export CSV file To export the CSV file, first of all, you need to add the dependencies of OpenCSV and import the required classes. import com.opencsv.CSVWriter; import java.io.FileWriter; import java.io.IOException; public class CSVExportExample { public static void main(String[] args) { CSVWriter writer = null; try { writer = new CSVWriter(new FileWriter("data.csv")); String [] header = {"name", "age", "city"}; writer.writeNext(header); String [] row1 = {"Zhang San", "25", "Beijing"}; String [] row2 = {"Li Si", "30", "Shanghai"}; String [] row3 = {"Wang Five", "35", "Guangzhou"}; writer.writeNext(row1); writer.writeNext(row2); writer.writeNext(row3); System.out.println ("CSV file has been successfully exported.");); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); } } } } In the above code, we first create a CSVWriter object to write to the CSV file.We then write the header and each line of data into files with the Writnext () method.In this example, we write three -line data, each line contains three fields.Finally, we turn off the writing device and print the news of the successful export. Summarize Using the OpenCSV framework can easily implement the introduction and export of CSV files.By reading CSV files with CSVReader, we can process data in the file one by one.By writing the CSV file with CSVWriter, we can output the data into the file in the specified format.