0

I have an Android project that displays data from a JSON file. The file is read from the assets directory, following the approach below:

src/main/assets/my_file.json

InputStream is = getResources().getAssets().open(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// use StringBuilder to get file contents as String

I also have local unit tests which require the same JSON file. In order to avoid the slowness of Instrumentation tests, I am currently loading a duplicate of the file as below:

src/main/resources/my_copy.json

File testData = new File(getClass().getResource(filename).getPath());
InputStream is = new FileInputStream(testData);
// read File as before

Is there an approach that would allow the JSON file to be stored in one location, whilst running the unit tests on a local JVM?

fractalwrench
  • 4,028
  • 7
  • 33
  • 49

2 Answers2

0

If you're using Robolectric, see this answer.

Note that the "assets" directory is an Android concept, it's different from Java resources. That said, you could also move your JSON file from assets to resources, and use it from both Android and JVM form there like you would in any Java application.

Community
  • 1
  • 1
sschuberth
  • 28,386
  • 6
  • 101
  • 146
0

Files in the resource directory can be accessed within Android applications by using ClassLoader#getResourceAsStream(). This returns an InputStream, which can then be used to read the file. This avoids having to duplicate files between resources and the assets directory.

InputStream is = getClass().getClassLoader().getResourceAsStream("my_file.json");
BufferedReader br = new BufferedReader(new InputStreamReader(is));

String line = null;
StringBuilder sb = new StringBuilder();

while ((line = br.readLine()) != null) {
    sb.append(line);
    }
}
String json = sb.toString();
fractalwrench
  • 4,028
  • 7
  • 33
  • 49