2

I have Json file (test.txt) and I wanna get data from that file to Android App. My code is:

private static String url = "file:///AndroidJSONParsingActivity/res/raw/test.txt";

But it is not working. Error I get is:

error opening trace file: No such file or directory (2)

Somebody help me? Thanks!

Abhay Kumar
  • 1,582
  • 1
  • 19
  • 45
binhnt
  • 97
  • 3
  • 11

5 Answers5

4

Put the test.txt file into assets folder

public class Utility {
   public static String readXMLinString(String fileName, Context c) {
      try {
          InputStream is = c.getAssets().open(fileName);
          int size = is.available();
          byte[] buffer = new byte[size];
          is.read(buffer);
          is.close();
          String text = new String(buffer);

          return text;
      } catch (IOException e) {
          throw new RuntimeException(e);
      }
   }
}

Then you can get test.txt using the following code

JSONObject json = new JSONObject(Utility.readXMLinString("test.txt",getApplicationContext()));
Franz Andel
  • 1,326
  • 12
  • 20
1

You have an answere Using JSON File in Android App Resources

You need to put the file intro raw folder and you can acces with this:

getResources().openRawResource(resourceName)
Community
  • 1
  • 1
Pipeline
  • 567
  • 1
  • 8
  • 23
0

use getResources().openRawResource(RawResource_id) for reading an text file from res/raw folder as:

 InputStream inputStream = Current_Activity.this.
                            getResources().openRawResource(R.raw.test);
 //put  your code for reading json from text file(inputStream) here
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
0

use following code to open input stream for the file stored in the raw folder:

getResources().openRawResource(R.raw.text_file)
Praful Bhatnagar
  • 7,425
  • 2
  • 36
  • 44
0

Please see below code for that, it will solve your problem.

public void mReadJsonData() {
    try {
        InputStream is = getResources().openRawResource(R.raw.textfilename)
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        String mResponse = new String(buffer);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128