如何从我的android测试项目的assets文件夹加载文件?

Al *_*aba 5 android android-testing

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

这样我加载输入流

    InputStream in2 = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
Run Code Online (Sandbox Code Playgroud)

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

File f = new File("assets/example.stf2");
Run Code Online (Sandbox Code Playgroud)

Al *_*aba 9

Found a soltion which works in my case, mabye someone else can use this as well.

Retrieving the file from my android test project to an inputstream

InputStream input = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
Run Code Online (Sandbox Code Playgroud)

Create a file on the External-Cachedir of the android application under test

File f = new File(getInstrumentation().getTargetContext().getExternalCacheDir() +"/test.txt");
Run Code Online (Sandbox Code Playgroud)

Copy the inputstream to the new file

FileUtils.copyInputStreamToFile(input, f);
Run Code Online (Sandbox Code Playgroud)

Now I can use this file for my further tests


dug*_*ggu 0

尝试下面的代码:-

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;
}
Run Code Online (Sandbox Code Playgroud)

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

如何将资产文件夹中的文件路径传递给文件(字符串路径)?