0

I want to return file object from assests folder. In Similar questions's response, it's returned InputStream class object, but I don't want to read content.

What I try to explain, there is an example.eg file in assests folder. I need to state this file as File file = new File(path).

ismael92
  • 33
  • 1
  • 6
  • possible duplicate of [How to get the android Path string to a file on Assets folder?](http://stackoverflow.com/questions/8474821/how-to-get-the-android-path-string-to-a-file-on-assets-folder) – CommonsWare Apr 22 '14 at 16:49

3 Answers3

1

Try this:

try {
  BufferedReader r = new BufferedReader(new InputStreamReader(getAssets().open("example.csv")));
  StringBuilder content = new StringBuilder();
  String line;
  while ((line = r.readLine()) != null) {
                content(line);
  }
} catch (IOException e) {
  e.printStackTrace();
}
Sergey Neskoromny
  • 1,188
  • 8
  • 15
0

As far as I know, assets are not regular accessible files like others. I used to copy them to internal storage and then use them. Here is the basic idea of it:

    final AssetManager assetManager = getAssets();
    try {
        for (final String asset : assetManager.list("")) {
            final InputStream inputStream = assetManager.open(asset);
            // ...
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
shkschneider
  • 17,833
  • 13
  • 59
  • 112
-3

You can straight way create a file using InputStream.

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;
}
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295