gpt4 book ai didi

java - 如何在java中有效解析巨大的csv文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:01 24 4
gpt4 key购买 nike

我的应用程序当前正在使用 CSV 解析器来解析 csv 文件并 持久化到数据库。它将整个 csv 加载到内存中并占用大量资源 时间的坚持,有时甚至会超时。我在网站上看到过
看到使用 Univocity 解析器的混合建议。请咨询 处理大量数据且花费更少时间的最佳方法。
谢谢。

代码:

 int numRecords = csvParser.parse( fileBytes );

public int parse(InputStream ins) throws ParserException {
long parseTime= System.currentTimeMillis();
fireParsingBegin();
ParserEngine engine = null;
try {
engine = (ParserEngine) getEngineClass().newInstance();
} catch (Exception e) {
throw new ParserException(e.getMessage());
}
engine.setInputStream(ins);
engine.start();
int count = parse(engine);
fireParsingDone();
long seconds = (System.currentTimeMillis() - parseTime) / 1000;
System.out.println("Time taken is "+seconds);
return count;
}


protected int parse(ParserEngine engine) throws ParserException {
int count = 0;
while (engine.next()) //valuesString Arr in Engine populated with cell data
{
if (stopParsing) {
break;
}

Object o = parseObject(engine); //create individual Tos
if (o != null) {
count++; //count is increased after every To is formed
fireObjectParsed(o, engine); //put in into Bo/COl and so valn preparations
}
else {
return count;
}
}
return count;

最佳答案

univocity-parsers 是加载 CSV 文件的最佳选择,您可能无法更快地手动编写任何代码。您遇到的问题可能来自两件事:

1 - 加载内存中的所有内容。这通常是一个糟糕的设计决策,但如果您这样做,请确保为您的应用程序分配了足够的内存。给它更多内存例如使用标志 -Xms8GXmx8G

2 - 您可能没有对插入语句进行批处理。

我的建议是尝试这个(使用 univocity-parsers):

    //configure input format using
CsvParserSettings settings = new CsvParserSettings();

//get an interator
CsvParser parser = new CsvParser(settings);
Iterator<String[]> it = parser.iterate(new File("/path/to/your.csv"), "UTF-8").iterator();

//connect to the database and create an insert statement
Connection connection = getYourDatabaseConnectionSomehow();
final int COLUMN_COUNT = 2;
PreparedStatement statement = connection.prepareStatement("INSERT INTO some_table(column1, column2) VALUES (?,?)");

//run batch inserts of 1000 rows per batch
int batchSize = 0;
while (it.hasNext()) {
//get next row from parser and set values in your statement
String[] row = it.next();
for(int i = 0; i < COLUMN_COUNT; i++){
if(i < row.length){
statement.setObject(i + 1, row[i]);
} else { //row in input is shorter than COLUMN_COUNT
statement.setObject(i + 1, null);
}
}

//add the values to the batch
statement.addBatch();
batchSize++;

//once 1000 rows made into the batch, execute it
if (batchSize == 1000) {
statement.executeBatch();
batchSize = 0;
}
}
// the last batch probably won't have 1000 rows.
if (batchSize > 0) {
statement.executeBatch();
}

这应该执行得很快,而且你甚至不需要 100mb 的内存来运行。

为了清楚起见,我没有使用任何 try/catch/finally block 来关闭此处的任何资源。您的实际代码必须能够处理该问题。

希望有帮助。

关于java - 如何在java中有效解析巨大的csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53048441/

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