Open Read Share Assets Folder Files Android

Android – How to read & share file from assets folder

In most of the applications there is a need to include files like database, files, audio, images in apk.  This can be achieved by saving files either inside assets or raw folder. Both folders can be used to store files and there is a very slight difference between the two.

raw is a subfolder of resources and Android source compilation automatically generates resource ID for any file present in raw folder. So the files can easily be referenced by their generated IDs. While, files stored in asset folder are accessed by the filenames and there is no reference created for these files. Other difference is that files can be grouped in sub folders inside assets while raw folder follows a flat hierarchy.

In this post we will see how to read and share files from assets as well as raw folder.

How to read file from Assets folder

Let’s check first where to keep assets folder. In order to save files in your application first create assets folder inside your apps main directory. Create assets folder inside app/src/main/ folder. You can create subfolders and save files.

Using Apache IOUtils

Add Apache Common IOUtils dependency in app’s gradle file.

Call IOUtils toString function to read from InputStream.

Using BufferedReader

Read file from Raw folder

Similar to assets folder inputstream can be opened for raw folder. Use openRawResource to create inputstream.

Share files saved in Assets folder

Android do not allow and expose files stored in assets. To allow sharing of files included in assets, app has to expose these files by creating a ContentProvider. Content Provider is used to share data between applications.

Add no compress options in the gradle file inside android block to disable compression of text, json files.

This will make sure that files inside asset folder are not compressed.

Full sample of app.gradle file

Now create our ContentProvider class that will handle the file sharing. In the ContentProvider we will override openAssetFile to create FileDescriptor for assets files.

Create MyContentProvider.java and paste the below content.

openAssetFile is implemented by providers that need to be able to return sub-sections of files, often assets inside of their .apk.

Add ContentProvider tag in AndroidManifest.xml

Replace android:authorities value with your package id.

Now we are ready to share files from assets directory. In your activity class you can share file as shown in the code below.

Share files from assets folder in Android

If you have a file example_2.json inside assets/subfolder then pass the file name like the snipped shared below.

 

 

3 Comments

  1. gil August 26, 2019
    • T M August 29, 2019
  2. Han September 3, 2019

Leave a Reply