简体   繁体   English

如何从Android应用程序中的文本文件读取大json?

[英]How to read a large json from a text file in android app?

I have a text file in my android app which consist a json. 我的Android应用中有一个包含json的文本文件。 I need to read and parse that json. 我需要阅读并解析该json。 File size is 21 mb. 文件大小为21 mb。 I am using following code to read file: 我正在使用以下代码读取文件:

 StringBuilder stringBuilder = new StringBuilder();
 InputStream input = getAssets().open(filename);
 int size = input.available();
 byte[] buffer = new byte[size];
 byte[] tempBuffer = new byte[1024];
 int tempBufferIndex = 0;
 for(int i=0; i<size; i++){
    if(i == 0){
        tempBuffer[tempBufferIndex] = buffer[i];
    }else{
        int mod = 1024 % i;
        if(mod == 0){
            input.read(tempBuffer);
            stringBuilder.append(new String(tempBuffer));
            tempBufferIndex = 0;
        }
        tempBuffer[tempBufferIndex] = buffer[i];
    }
}
input.close();

Size int is 20949874 in real case. 大小为int的实际值为20949874。 After loop is done stringBuilder length is always 11264 even if i change range of for loop. 循环完成后,即使我更改for循环的范围,stringBuilder的长度也始终为11264。 I tried to make one String from InputStream without using loop but it always gives me OutOfMemoryError Exception. 我试图从InputStream制作一个String而不使用循环,但是它总是给我OutOfMemoryError异常。 I also get "Grow heap (frag case) to 26.668MB for 20949890-byte allocation" in my logs. 我的日志中还显示“将堆(碎片大小写)增长到26.668MB,以分配20949890字节”。 I searched here and tried different solutions but did not make it work. 我在这里搜索并尝试了不同的解决方案,但没有成功。 Any idea how should i solve this issue. 任何想法我应该如何解决这个问题。 Thanks in advance. 提前致谢。

For big json files you should use SAX parser and not DOM. 对于较大的json文件,您应该使用SAX解析器而不是DOM。 For example JsonReader . 例如JsonReader

DOM (“Document Object Model”) loads the entire content into memory and permits the developer to query the data as they wish. DOM (“文档对象模型”)将整个内容加载到内存中,并允许开发人员根据需要查询数据。 SAX presents the data as a stream: the developer waits for their desired pieces of data to appear and saves only the parts they need. SAX将数据显示为流:开发人员等待所需的数据出现,并仅保存所需的部分。 DOM is considered easier to use but SAX uses much less memory. DOM被认为更易于使用,但SAX使用的内存要少得多。

You can try to split the file into several parts. 您可以尝试将文件分成几个部分。 So during processing the app hopefully doesn't get out of memory. 因此,在处理应用程序期间,希望它不会耗尽内存。

You should also consider using "largeHeap" flag in your manifest (See http://developer.android.com/guide/topics/manifest/application-element.html ) 您还应该考虑在清单中使用“ largeHeap”标志(请参阅http://developer.android.com/guide/topics/manifest/application-element.html

I don't know your file, but maybe if you use smaller JSON tags, you can reduce storage as well. 我不知道您的文件,但是如果您使用较小的JSON标签,那么也可以减少存储量。

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

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