如何读取csv文件用java
时间: 2024-06-13 10:08:17 浏览: 163
java 读取写入csv
3星 · 编辑精心推荐
以下是两种Java读取CSV文件的方法:
1.使用Java自带的CSV库
```java
import java.io.BufferedReader;import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadCSV {
public static void main(String[] args) {
String csvFile = "path/to/csv/file.csv";
String line = "";
String cvsSplitBy = ",";
List<String[]> csvData = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] data = line.split(cvsSplitBy);
csvData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
}
// 打印读取到的数据
for (String[] data : csvData) {
for (String item : data) {
System.out.print(item + " ");
}
System.out.println();
}
}
}
```
2.使用OpenCSV库
```java
import com.opencsv.CSVReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
public class ReadCSV {
public static void main(String[] args) {
String csvFile = "path/to/csv/file.csv";
List<String[]> csvData = null;
try (CSVReader reader = new CSVReader(new FileReader(csvFile))) {
csvData = reader.readAll();
} catch (IOException e) {
e.printStackTrace();
}
// 打印读取到的数据
for (String[] data : csvData) {
for (String item : data) {
System.out.print(item + " ");
}
System.out.println();
}
}
}
```
阅读全文