0

I want to read json file which have large amount of data

My code

public String loadJSONFromAsset() {
        f = new File(Environment.getExternalStorageDirectory().getPath() + "/Contact Backup/name.json");
        String json = null;
        try {
            InputStream is;
            is = new BufferedInputStream(new FileInputStream(f));
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    } 

In my logcat, it shows only half json file was readed.

Any help?

Bala Raja
  • 627
  • 6
  • 20
  • 1
    Take a look on this(http://stackoverflow.com/questions/6164853/java-issue-with-available-method-of-bufferedinputstream , http://stackoverflow.com/questions/7874713/java-read-from-inputstream-doesnt-always-read-the-same-amount-of-data , https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#available()) You will know the problem of the available function – Long Ranger Sep 02 '16 at 03:39

2 Answers2

2

Do not read byte by byte , read lind by line using scanner class.

Example

public String loadJSONFromAsset() {
   file = new File(Environment.getExternalStorageDirectory().getPath() + "/Contact Backup/name.json");
   final StringBuilder text = new StringBuilder();
   try {
         Scanner sc = new Scanner(file);
         while (sc.hasNextLine()) {
            text.append(sc.nextLine());
         }
        sc.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
   return text.toString();
}
Yogesh Rathi
  • 6,331
  • 4
  • 51
  • 81
0

Actually Logcat will truncate any too long message. If you want to show all your messages, you can use below function:

final int chunkSize = 2048;
for (int i = 0; i < s.length(); i += chunkSize) {
    Log.d(TAG, s.substring(i, Math.min(s.length(), i + chunkSize)));
}

You can use above function to check whether your code is fine or not.

Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86