Home  >  Article  >  Java  >  Use OpenCSV to implement CSV file reading and writing functions in Java

Use OpenCSV to implement CSV file reading and writing functions in Java

PHPz
PHPzOriginal
2023-12-20 12:48:05656browse

在 Java 中利用 OpenCSV 实现 CSV 文件的读写功能

In Java, CSV files (Comma Separated Values ​​Files) are a common data storage and exchange format. When working with CSV files, you usually need to read and write the file. OpenCSV is a popular Java library that can easily implement the reading and writing functions of CSV files. This article will use OpenCSV to introduce how to read and write CSV files in Java.

First, we need to add the dependency of the OpenCSV library to the Java project. You can add dependencies in the Maven project in the following ways:

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.5</version>
</dependency>

After adding the dependencies, we can start using OpenCSV to read and write CSV files. First, let's take a look at how to read CSV files using OpenCSV.

Read CSV file

Suppose we have a CSV file named "example.csv" with the following content:

Name,Age,City
John,25,New York
Alice,30,Seattle
Bob,28,Chicago

We can use OpenCSV to read and parse the The contents of the file. First, create a CSVReader object and pass in the path of the file as a parameter:

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("example.csv"))) {
            String[] nextLine;
            while ((nextLine = reader.readNext()) != null) {
                for (String cell : nextLine) {
                    System.out.print(cell + " ");
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above code, we read the CSV file by creating a CSVReader object and parse the file content line by line. Each time the readNext() method is called, one row of data will be returned as a String array. Then we iterate through the array and output the contents of each cell.

Write CSV files

In addition to reading CSV files, OpenCSV also provides the function of writing CSV files. We can write data to CSV files through CSVWriter.

Suppose we want to write some data to a file named "output.csv", the code is as follows:

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[] data1 = {"Name", "Age", "City"};
            String[] data2 = {"Tom", "29", "Los Angeles"};
            String[] data3 = {"Emily", "27", "San Francisco"};
            writer.writeNext(data1);
            writer.writeNext(data2);
            writer.writeNext(data3);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above code, we created a CSVWriter object to implement CSV file writes data. Use the writeNext() method to write the data in the String array to a file and add a newline character to the file.

Through the above introduction, we have learned how to use the OpenCSV library in Java to implement the reading and writing functions of CSV files. By using OpenCSV, we can easily process CSV files, read the data in them and write data to the file. This provides convenience for us to process CSV files in Java projects, allowing us to focus on the implementation of business logic without spending too much energy on file operations.

The above is the detailed content of Use OpenCSV to implement CSV file reading and writing functions in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn