【问题标题】:How to load a file from assets folder of my android test project?如何从我的 android 测试项目的 assets 文件夹中加载文件?
【发布时间】:2014-04-29 09:52:44
【问题描述】:

有没有办法获取资产文件夹中的一个文件的文件对象。我知道如何加载此类文件的输入流,但我需要一个文件对象而不是输入流。

这样我加载输入流

    InputStream in2 = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");

但我需要文件对象,这样找不到文件

File f = new File("assets/example.stf2");

【问题讨论】:

标签: android android-testing


【解决方案1】:

找到了一个适用于我的解决方案,也许其他人也可以使用它。

将文件从我的 android 测试项目中检索到输入流

InputStream input = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");

在被测android应用的External-Cachedir上创建一个文件

File f = new File(getInstrumentation().getTargetContext().getExternalCacheDir() +"/test.txt");

将输入流复制到新文件

FileUtils.copyInputStreamToFile(input, f);

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

【讨论】:

  • 我找这个已经很久了!!非常感谢,运行良好!
【解决方案2】:

试试下面的代码:-

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;
}

欲了解更多信息,请参阅以下链接:-

How to pass a file path which is in assets folder to File(String path)?

【讨论】:

  • 这不起作用,因为 File f = new File(my_file_name);无法创建,在这种情况下,文件名的有效路径是什么?我用 assets/test.txt 试过了
猜你喜欢
  • 2011-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
相关资源
最近更新 更多