Java如何读取.csv文件信息
时间: 2024-12-05 16:13:35 浏览: 20
在Java中,我们可以使用开源库如Apache Commons CSV、OpenCSV或者是最近的JDK自带的流式API(since Java 7)来读取.csv文件。以下是使用三种常见库的一种简单示例:
1. **使用Apache Commons CSV**:
```java
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import java.io.FileReader;
public class CsvReader {
public static void main(String[] args) {
try (CSVParser parser = CSVParser.parse(new FileReader("file.csv"), CSVFormat.DEFAULT)) {
for (CSVRecord record : parser) {
String column1 = record.get(0);
String column2 = record.get(1); // 假设.csv文件有两列
System.out.println(column1 + ", " + column2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. **使用OpenCSV**:
```java
import com.opencsv.CSVReader;
import java.io.FileReader;
public class OpenCsvReader {
public static void main(String[] args) throws Exception {
CSVReader reader = new CSVReader(new FileReader("file.csv"));
String[] line;
while ((line = reader.readNext()) != null) {
System.out.println(line[0] + "," + line[1]);
}
reader.close();
}
}
```
3. **使用Java 7+的Stream API** (如果.csv文件非常大且适合流处理):
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.stream.Collectors;
public class StreamCsvReader {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("file.csv"))) {
String line;
while ((line = br.readLine()) != null) {
String[] columns = line.split(",");
// 使用collect处理每一行数据
System.out.println(columns[0] + "," + columns[1]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文