0

I am trying to read an assets file using InputStream but it throws OutOfMemory Exception , the size of file is 22 mb ( about 22 Million Bytes ! )

This is the code I use

try{
    java.io.InputStream is = MainActivity.this.getAssets().open("file.json");
               int Si = is.available();
               byte[] Bu = new byte[Si];
               is.read(Bu);
               is.close();
               data = new String(Bu, "UTF-8");
}catch(Exception e){
     
}
Arab Ware
  • 9
  • 4
  • But why would you place a big file completely in a byte buffer in memory? Makes ni sense to me. And not enough: After that you create a string fir that byte buffer. Hence it would be in memory twice. Wonder why you are doing this. – blackapps Aug 19 '22 at 14:34
  • separate to several files – Style-7 Aug 19 '22 at 14:35
  • Well even then that is not needed. And converting a byte buffer to string neither. You mean 22 MB. Not 22 mb. – blackapps Aug 19 '22 at 14:36
  • 1
    You may not be able to hold 22MB of parsed JSON in memory. But, you will have better luck if you pass the `InputStream` to your JSON parser (Moshi, Gson, Jackson, etc.), rather than trying to read it in yourself. – CommonsWare Aug 19 '22 at 14:44
  • Could please refer to method name or something in the gson library that read directly from inputstream? – Arab Ware Aug 19 '22 at 15:22
  • 1
    Like @CommonsWare correctly said lots of library do provide option to read large Json files using Streams, however that also depends on your Json Structure, assuming it would be a big array of lots of similar Json Structures(Objects) it would be possible to use these libraries. – Piyush Saxena Aug 19 '22 at 15:35
  • 1
    Use `fromJson()` on a `Gson` instance, wrapping your `InputStream` in an `InputStreamReader`. See https://github.com/google/gson/issues/187#issuecomment-83702155 – CommonsWare Aug 19 '22 at 16:49

2 Answers2

0

As @CommonsWare said , just I have to use this

((java.io.Reader)(new java.io.InputStreamReader(ContextOfClass.getAssests().open("file name"))))

In my gson json to listmap/liststring/etc code

Arab Ware
  • 9
  • 4
-1

add android:largeHeap="true" in your manifest file

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

Refer to this answer

make sure you don't have two copies of the data in memory. You can null out the reference to the old ArrayList before starting to create the new one, though you have to do that carefully -- calling ArrayList.clear() first would be more thorough.

Sidharth Mudgil
  • 1,293
  • 8
  • 25