Use OpenCSV to read and write CSV files in Java
CSV (Comma-separated values) files are a common data storage format, in which Different data items are separated by commas. When dealing with CSV files, we need the ability to read and write files in this format. In Java, we can use the OpenCSV library to accomplish these tasks.
OpenCSV is a Java library that provides a simple and easy-to-use API for reading and writing CSV files. It provides various features like custom separators, skip rows, skip empty rows, read specific columns, etc.
First, we need to introduce the OpenCSV library into the project. The following Maven dependencies can be added to the project's pom.xml file:
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.3</version> </dependency>
Next, we can start using OpenCSV to read and write CSV files.
Read CSV file:
import com.opencsv.CSVReader; import java.io.FileReader; import java.io.IOException; import java.util.List; public class CSVReaderExample { public static void main(String[] args) { try (CSVReader reader = new CSVReader(new FileReader("data.csv"))) { List<String[]> records = reader.readAll(); for (String[] record : records) { for (String field : record) { System.out.print(field + " "); } System.out.println(); } } catch (IOException e) { e.printStackTrace(); } } }
The above code will print out all data items in the CSV file. Among them, the CSVReader class is used to read CSV files, and the readAll() method returns a Listd8e50004b3852d85b72500fd6e9ac257 object, where each String[] array represents a row of data. By traversing this List, we can print out all data items one by one.
Write CSV file:
import com.opencsv.CSVWriter; import java.io.FileWriter; import java.io.IOException; public class CSVWriterExample { public static void main(String[] args) { try (CSVWriter writer = new CSVWriter(new FileWriter("output.csv"))) { String[] record1 = {"John", "Doe", "john.doe@example.com"}; String[] record2 = {"Jane", "Smith", "jane.smith@example.com"}; writer.writeNext(record1); writer.writeNext(record2); } catch (IOException e) { e.printStackTrace(); } } }
The above code will generate a file named output.csv and write the data items in record1 and record2 into it. The CSVWriter class is used to write CSV files. The writeNext() method can pass in a String[] array and write it to the file.
Through the OpenCSV library, we can easily read and write CSV files. Whether we are processing large data sets or small data files, OpenCSV provides an efficient and easy-to-use API to help us complete the task. Using OpenCSV, we can easily process CSV files in Java and import and export data, thus providing more convenience for our data processing work.
The above is the detailed content of Reading and writing CSV files in Java using OpenCSV. For more information, please follow other related articles on the PHP Chinese website!