Example of using OpenCSV to read and write CSV files in Java
CSV (Comma-Separated Values) refers to comma-separated values, which is a Common data storage formats. In Java, OpenCSV is a commonly used tool library for reading and writing CSV files. This article will introduce how to use OpenCSV to implement examples of reading and writing CSV files.
First, you need to introduce the OpenCSV library into the project. The OpenCSV library can be introduced through Maven or manually downloading the jar package.
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.5</version> </dependency>
Here is a sample code for reading a CSV file using OpenCSV:
import com.opencsv.CSVReader; import java.io.FileReader; import java.io.IOException; public class CSVReaderExample { public static void main(String[] args) { try { CSVReader reader = new CSVReader(new FileReader("input.csv")); String[] nextLine; while ((nextLine = reader.readNext()) != null) { for (String cell : nextLine) { System.out.print(cell + " "); } System.out.println(); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } }
In the above example, we First, a CSVReader
object is created, and then the readNext
method is used to read the data in the CSV file line by line, and each line of data is returned in the form of an array. Finally, the data of each cell is printed out by traversing the array.
Next is a sample code for writing a CSV file using OpenCSV:
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[] record = {"Name", "Age", "Gender"}; writer.writeNext(record); String[] record1 = {"Alice", "25", "Female"}; writer.writeNext(record1); String[] record2 = {"Bob", "30", "Male"}; writer.writeNext(record2); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
In the above example, we First, a CSVWriter
object is created, and then the header and data records of the CSV file are written using the writeNext
method.
If you use Maven for management, add the following dependencies in the pom.xml file:
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.5</version> </dependency>
In this article, we introduce An example of how to use the OpenCSV library to read and write CSV files. Through the OpenCSV library, you can easily operate CSV files and import and export data conveniently. Hope this article helps you!
The above is the detailed content of Example of reading and writing CSV files using OpenCSV in Java. For more information, please follow other related articles on the PHP Chinese website!