Al Phaba
Al Phaba

Reputation: 6785

How to load a file from assets folder of my android test project?

Is there a way to get the file object of one of the files which are inside the assets folder. I know how to load the inputstream of such a file, but i need to have a file object instead of the inputstream.

This way i load the inputstream

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

But I need the file object, this way the file will not be found

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

Upvotes: 7

Views: 5989

Answers (2)

Al Phaba
Al Phaba

Reputation: 6785

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");

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

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

Copy the inputstream to the new file

FileUtils.copyInputStreamToFile(input, f);

Now I can use this file for my further tests

Upvotes: 12

duggu
duggu

Reputation: 38439

try below code:-

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

for more info see below link :-

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

Upvotes: 0

Related Questions