Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中高效解析巨大的csv文件_Java_Csv_Parsing - Fatal编程技术网

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

如何在java中高效解析巨大的csv文件,java,csv,parsing,Java,Csv,Parsing,我的应用程序目前正在使用CSV解析器解析CSV文件和 保存到数据库。它将整个csv加载到内存中,占用了大量时间 坚持的时间,有时甚至超时。我在网站上看到过 看到使用Univocity解析器的混合建议。请建议 处理大量数据的最佳方法,耗时更少。 多谢各位 代码: 使用Apache提供的库。univocity解析器是加载CSV文件的最佳选择,您可能无法更快地手工编写代码。您遇到的问题可能来自两个方面: 1-加载内存中的所有内容。这通常是一个糟糕的设计决策,但如果这样做,请确保为应用程序分配足够的内存

我的应用程序目前正在使用CSV解析器解析CSV文件和 保存到数据库。它将整个csv加载到内存中,占用了大量时间 坚持的时间,有时甚至超时。我在网站上看到过
看到使用Univocity解析器的混合建议。请建议 处理大量数据的最佳方法,耗时更少。
多谢各位

代码:


使用Apache提供的库。

univocity解析器是加载CSV文件的最佳选择,您可能无法更快地手工编写代码。您遇到的问题可能来自两个方面:

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

2-您可能没有批处理insert语句

我的建议是尝试(使用univocity解析器):

//使用配置输入格式
CsvParserSettings=新CsvParserSettings();
//找一个内部人员
CsvParser parser=新的CsvParser(设置);
Iterator it=parser.iterate(新文件(“/path/to/your.csv”),“UTF-8”).Iterator();
//连接到数据库并创建insert语句
Connection Connection=GetYourDatabaseConnectionsHomeHow();
最终整数列_计数=2;
PreparedStatement=connection.prepareStatement(“插入到某些表(第1列、第2列)的值(?)”;
//每批运行1000行的批插入
int batchSize=0;
while(it.hasNext()){
//从解析器中获取下一行并在语句中设置值
String[]row=it.next();
对于(inti=0;i0){
语句。executeBatch();
}
这应该执行得很快,运行时甚至不需要100mb内存

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


希望能有所帮助。

有不同的方法读取性能被注释的文件。具体取决于应用程序。。我认为在大多数情况下,瓶颈在于将数据持久化,而不是从csv文件中读取数据。鉴于文件很大,您可能只想将部分csv数据加载到内存中,以确保不受内存限制。“它将整个csv加载到内存中”← 这就是你问题的原因。不要那样做。阅读后解析每一行。InputStreams和Reader的全部要点是在内存中拥有可管理的数据量。感谢您的回答。我已经用mycode更新了这个问题。我们正在转换为filebytes并调用解析(byte bytes[])。我需要在这里更改我的实现吗?您可以参考任何示例代码吗?有没有一种方法可以在java中以块的形式发送文件字节进行解析?谢谢Jeronimo。应用程序已经在使用-Xms8G和Xmx8G。我将尝试使用您建议的批处理实现。再次感谢您的输入。嗨,Jeronimo,我看了代码,我们正在使用CSVParser和Parseorbserver,csv文件中的每一行都需要1秒来解析和验证。但对于一个有120k条记录的文件来说,完成上传到数据库大约需要1个多小时,因为它总是以串行方式处理的。你能建议一些并行实现的方法吗?另外,我的应用程序使用了-Xms8G和-Xms24GUnivocity解析器没有parserobserver类。您使用的是正确的库吗?您应该在不到2秒(csv)的时间内处理120k条记录,并且最多需要10秒才能将其全部插入数据库。
 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;
    //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();
    }