如何读取的src / instrumentTest /资源目录中的Andr​​oid文件? [英] How to read a file from src/instrumentTest/resources directory in Android?

查看:183
本文介绍了如何读取的src / instrumentTest /资源目录中的Andr​​oid文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用新的标准摇篮布局的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.

这篇关于如何读取的src / instrumentTest /资源目录中的Andr​​oid文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆