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,522
  • 1
  • 18
  • 43
binhnt
  • 103
  • 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,176
  • 9
  • 18
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
  • 130,641
  • 51
  • 193
  • 212
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,450
  • 2
  • 35
  • 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,009
  • 18
  • 75
  • 127