【发布时间】:2019-04-02 13:24:17
【问题描述】:
我的应用程序当前正在使用 CSV Parser 来解析 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;
【问题讨论】:
-
有不同的方式来读取文件,性能在this other SO question中被评论。
-
取决于应用程序。我认为在大多数情况下,瓶颈会将数据推送到持久性而不是从 csv 文件中读取。鉴于文件很大,您可能只想将部分 csv 数据加载到内存中,以确保您不受内存限制。
-
“它将整个 csv 加载到内存中” ← 这就是你的问题的原因。不要那样做。阅读后解析每一行。 InputStreams 和 Readers 的重点是在内存中拥有可管理的数据量。
-
感谢您的回复。我已使用 mycode 更新了问题。我们正在转换为文件字节并调用 parse(byte bytes[])。我需要在这里更改我的实现吗?有没有可以参考的示例代码?
-
有没有办法在java中以块的形式发送文件字节进行解析?