gpt4 book ai didi

java - 在 java 中读取大型 CSV

转载 作者:搜寻专家 更新时间:2023-10-31 08:19:57 24 4
gpt4 key购买 nike

我想从 CSV 中读取大量数据,其中包含大约 500,000 行。我正在为此使用 OpenCSV 库。我的代码是这样的

    CsvToBean<User> csvConvertor = new CsvToBean<User>();
List<User> list = null;
try {
list =csvConvertor.parse(strategy, new BufferedReader(new FileReader(filepath)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}

最多 200,000 条记录,数据被读入用户 bean 对象列表。但是对于比我得到的更多的数据

java.lang.OutOfMemoryError: Java heap space

我在“eclipse.ini”文件中有这个内存设置

-Xms256m
-Xmx1024m

我正在考虑将大文件拆分为单独文件并再次读取这些文件的解决方案,我认为这是一个冗长的解决方案。

有没有其他方法可以避免 OutOfMemoryError 异常。

最佳答案

逐行阅读

像这样

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}

关于java - 在 java 中读取大型 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20043181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com