How to read a file from src / instrumentTest / resources directory in Android?

I have an Android app using the new standard gradle layout:

  src / main / java
  src / main / resources
  src / instrumentTest / java
  src / instrumentTest / resources

I have a unit test in src/instrumentTest/java/com/example/MyUnitTest.javathat reads a file located in src/instrumentTest/resources/testfile.json

  • First question: the right place to place test files?
  • Second question: how can I read this file in String?

I tried these two ways to read the file in unit test without success (it cannot find the file):

String myJson = new Scanner (new File ("testfile.json"), "UTF-8"). UseDelimiter ("\\ A"). Next ();

String myJson = new Scanner (new File ("resources / testfile.json"), "UTF-8"). UseDelimiter ("\\ A"). Next ();

Hooray!

+3
1

, . ( ):

src/debug/res/assets

InputStream raw = context.getAssets().open("filename.ext");
String myJson = new Scanner(raw).useDelimiter("\\A").next();

apk.

+5

All Articles