Java读取大文件csv
时间: 2023-08-27 22:05:09 浏览: 137
Java中使用opencsv读写csv文件示例
5星 · 资源好评率100%
读取大文件的CSV可以使用Java的BufferedReader和Scanner类。以下是使用BufferedReader读取大文件的CSV的示例代码:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadCSV {
public static void main(String[] args) {
String csvFile = "path/to/your/file.csv";
String line = "";
String cvsSplitBy = ",";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] data = line.split(cvsSplitBy);
// do something with the data
System.out.println("Data: " + data[0] + " " + data[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
另一种方法是使用Scanner类,以下是示例代码:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadCSV {
public static void main(String[] args) throws FileNotFoundException {
String csvFile = "path/to/your/file.csv";
Scanner scanner = new Scanner(new File(csvFile));
scanner.useDelimiter(",");
while (scanner.hasNext()) {
String data = scanner.next();
System.out.println("Data: " + data);
}
scanner.close();
}
}
```
这些示例代码可以读取大型CSV文件而不会导致内存不足异常。
阅读全文