如何读取的src / instrumentTest /资源目录中的Andr​​oid文件?文件、资源、目录中、instrumentTest

2023-09-06 18:16:22 作者:┌.┌.ㄝん.ˋ.

我必须使用新的标准摇篮布局的Andr​​oid应用程序:

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


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

我在的src / instrumentTest /的Java / COM /例子/ MyUnitTest.java 读取位于文件的src / instrumentTest单元测试/resources/testfile.json

第一个问题:是不是在正确的地方放置测试文件 第二个问题:我如何可以读取文件中的一个字符串

我已经试过这两种方式读取的单元测试文件,但没有成功(无法找到文件):

I have tried these two ways for reading the file in the unit test with no 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();

干杯!

推荐答案

您可以使用生成类型您正在测试的资产文件夹。如果您正在测试调试类型(这是默认的):

You can use the assets folder of the build type your are testing. If you are testing the debug type (which is the default one):

src/debug/res/assets

然后你访问这些文件。

And then you access those files with

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

使用的伎俩的调试的生成类型$ P ​​$ pvent您的测试资源被包装在最后的apk。

The trick of using the debug build type prevent your testing resources to be packed in the final apk.