7

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");
Al Phaba
  • 6,545
  • 12
  • 51
  • 83
  • You can't get file object refer to asset. you should copy InputStream. Refere : http://stackoverflow.com/questions/10402690/android-how-do-i-create-file-object-from-asset-file – jignesh.world Apr 29 '14 at 10:33

2 Answers2

12

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

Al Phaba
  • 6,545
  • 12
  • 51
  • 83
0

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)?

Community
  • 1
  • 1
duggu
  • 37,851
  • 12
  • 116
  • 113
  • This does not work because the File f = new File(my_file_name); cannot be created, what is a valid path in that case for the filename? I tried it with assets/test.txt – Al Phaba Apr 29 '14 at 10:04