简体   繁体   English

Android读取大文件

[英]Android reading a large file

I have a CSV file in the assets folder with more than 10000 lines of data. 我在assets文件夹中有一个包含10000多行数据的CSV文件。 I want to insert this data into a SQLite database when the database is created. 我想在创建数据库时将此数据插入到SQLite数据库中。 I cannot include a database because it is a very generic application and the model demands a CSV file instead. 我不能包含数据库,因为它是一个非常通用的应用程序,而且模型需要CSV文件。 I don't want to read all 10000 lines of data and insert it from the memory in one stretch. 我不想读取所有10000行数据并将其从内存中插入一段。 How do I accomplish the task effectively and efficiently? 如何有效地完成任务?

Just insert immediately once you've read the line. 只需在读完线后立即插入即可。 So, just don't store the lines in some arraylist in memory. 所以,只是不要将行存储在内存中的某些arraylist中。

Eg 例如

while ((line = reader.readLine()) != null) {
    insert(line);
}

You might want to do this in a single transaction so that you can rollback whenever it fails halfway. 您可能希望在单个事务中执行此操作,以便在中途失败时可以回滚。 In the JDBC side, you may want to consider PreparedStatement#addBatch() / #executeBatch() to execute the inserts in batches. 在JDBC方面,您可能需要考虑PreparedStatement#addBatch() / #executeBatch()来批量执行插入。 An example can be found in this answer . 这个答案中可以找到一个例子。

Update : as a completely different but more efficient alternative, you can also leave Java outside the story and use CSV import facility provided by SQLite . 更新 :作为一个完全不同但更有效的替代方案,您还可以将Java留在故事之外并使用SQLite提供的CSV导入工具

在这种情况下,最简单和最有效的是从文件中一次读取20-30-50行(或者可能是100行!)并插入到数据库中,但是您还需要运行一些测试来查看是什么您可以在1中读取的最佳行数然后执行:-)

IMPORT filename tablename IMPORT filename tablename

(from http://old.nabble.com/How-can-I-load-big-file-into-a-sqlite-database--td19202500.html - like LOAD DATA in mysql). (来自http://old.nabble.com/How-can-I-load-big-file-into-a-sqlite-database--td19202500.html - 就像mysql中的LOAD DATA一样)。

Other: disable auto commit, auto flush; 其他:禁用自动提交,自动刷新; read 20 lines, commit, flush. 读20行,提交,刷新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM