Question

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

Was it helpful?

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

OTHER TIPS

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

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();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top