如何从android测试项目的资产文件夹加载文件?

如何从android测试项目的资产文件夹加载文件?,android,android-testing,Android,Android Testing,是否有方法获取资产文件夹中某个文件的文件对象。我知道如何加载这样一个文件的inputstream,但是我需要一个file对象而不是inputstream 这样我就可以加载inputstream InputStream in2 = getInstrumentation().getContext().getResources().getAssets().open("example.stf2"); InputStream input = getInstrumentation().getCon

是否有方法获取资产文件夹中某个文件的文件对象。我知道如何加载这样一个文件的inputstream,但是我需要一个file对象而不是inputstream

这样我就可以加载inputstream

    InputStream in2 = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
InputStream input = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
但是我需要文件对象,这样就找不到文件

File f = new File("assets/example.stf2");
请尝试以下代码:-

AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

return null;
}
有关更多信息,请参阅以下链接:-


找到了一种对我有效的解决方案,也许其他人也可以使用

将文件从我的android测试项目检索到inputstream

    InputStream in2 = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
InputStream input = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
在测试中的android应用程序的外部Cachedir上创建一个文件

File f = new File(getInstrumentation().getTargetContext().getExternalCacheDir() +"/test.txt");
将inputstream复制到新文件

FileUtils.copyInputStreamToFile(input, f);

现在我可以使用此文件进行进一步的测试

这不起作用,因为文件f=新文件(我的文件名);无法创建,在这种情况下,文件名的有效路径是什么?我用assets/test.txt尝试了它。您无法获取引用asset的文件对象。您应该复制InputStream。我已经找了很久了!!非常感谢,它工作得很好!