161

I have been trying to get the URI path for an asset file.

uri = Uri.fromFile(new File("//assets/mydemo.txt"));

When I check if the file exists I see that file doesn't exist

File f = new File(filepath);
if (f.exists() == true) {
    Log.e(TAG, "Valid :" + filepath);
} else {
    Log.e(TAG, "InValid :" + filepath);
}

Can some one tell me how I can mention the absolute path for a file existing in the asset folder

13 Answers 13

189

There is no "absolute path for a file existing in the asset folder". The content of your project's assets/ folder are packaged in the APK file. Use an AssetManager object to get an InputStream on an asset.

For WebView, you can use the file Uri scheme in much the same way you would use a URL. The syntax for assets is file:///android_asset/... (note: three slashes) where the ellipsis is the path of the file from within the assets/ folder.

10
  • 35
    file://android_asset/..., where ... is the relative path within your project's assets/ directory. Jan 27, 2011 at 19:40
  • 5
    Here is a sample project using file://android_asset/, though not for a Uri: github.com/commonsguy/cw-advandroid/tree/master/WebView/GeoWeb1 Jan 27, 2011 at 19:56
  • 22
    @CommonsWare it looks like you missed a '/' in your URI. It should be file:///.
    – ThomasW
    Nov 4, 2011 at 7:20
  • 11
    I tried this as new File("file:///android_asset/sounds/beep.mid");, but result file doesn't exists. Any ideas? P.S. file is in assets/sounds/ folder.
    – uncle Lem
    May 14, 2014 at 0:15
  • 6
    Is it right that ´file:///android_asset/...´ works only in WebView and is not possible to get InputStream using URI/URL/Uri outside WebView?
    – Lubbo
    Apr 26, 2017 at 14:27
80

The correct url is:

file:///android_asset/RELATIVEPATH

where RELATIVEPATH is the path to your resource relative to the assets folder.

Note the 3 /'s in the scheme. Web view would not load any of my assets without the 3. I tried 2 as (previously) commented by CommonsWare and it wouldn't work. Then I looked at CommonsWare's source on github and noticed the extra forward slash.

This testing though was only done on the 1.6 Android emulator but I doubt its different on a real device or higher version.

EDIT: CommonsWare updated his answer to reflect this tiny change. So I've edited this so it still makes sense with his current answer.

2
  • 3
    Doesn't work anymore String fileName = "file:///android_asset/file.csv"; System.out.println(new File(fileName).exists()); // prints false
    – Elgirhath
    Jun 19, 2020 at 20:15
  • @Elgirhath the constructor for File that accepts a string is expecting a path not a URI. I haven't coded for Android for a few years and things may have changed. I'm unsure if you can access the embedded assets folder using a normal java File class. I seem to remember that you have to use an AssetManager. Files in the assets folder are placed on the device in the read-only bundled APK and compressed (APKs are actually zip files), thus more work to read it back. Try something like new File(new URI(filename))
    – Russ
    Jun 20, 2020 at 21:42
31

Finally, I found a way to get the path of a file which is present in assets from this answer in Kotlin. Here we are copying the assets file to cache and getting the file path from that cache file.

@Throws(IOException::class)
    fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
            .also {
               if (!it.exists()) {
                it.outputStream().use { cache ->
                    context.assets.open(fileName).use { inputStream ->
                            inputStream.copyTo(cache)
                    }
                  }
                }
            }

Get the path to the file like:

val filePath =  getFileFromAssets(context, "fileName.extension").absolutePath
9
  • 1
    Notice that if the fileName have directory dir/file. It will crash with path the cache/dir/file not exist. Also I think better have a checking if(!it.exist) inside the also block, then it will not copy the file every time even the file is already on the cache
    – Yeung
    Sep 27, 2019 at 9:55
  • @ShylendraMadda, @Yeung, if(!it.exist) thows an error unresolved reference. any solution ?
    – binrebin
    May 29, 2020 at 10:03
  • Check that file exists in your cache with that file name? @binrebin May 29, 2020 at 12:58
  • @ShylendraMadda, I know filename only. Can we load it with script without knowing actual uri
    – binrebin
    May 29, 2020 at 17:32
  • 2
    for someone if have some dir before the file name, like -> ("raw/filename.ext" ), inside if (!it.exists()) block befor the it.outputStream().use { cache -> ... add this code to create directory if is not exist --> val fileDir = File( context.cacheDir, File.separator.toString() + "raw" ) fileDir.mkdir()
    – A S A D I
    Jul 19, 2022 at 6:01
15

Please try this code working fine

 Uri imageUri = Uri.fromFile(new File("//android_asset/luc.jpeg"));

    /* 2) Create a new Intent */
    Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
            .setData(imageUri)
            .build();
7

enter image description here

Be sure ,your assets folder put in correct position.

2
  • 2
    You can put it wherever you want and define the path in your build.gradle file as follows sourceSets { main { assets.srcDirs = ['src/main/assets'] } }
    – Marcel Bro
    Nov 13, 2018 at 12:40
  • 6
    How to get path of hello.html ? please add Feb 6, 2019 at 18:53
6

Works for WebView but seems to fail on URL.openStream(). So you need to distinguish file:// protocols and handle them via AssetManager as suggested.

3

Try this out, it works:

InputStream in_s = 
    getClass().getClassLoader().getResourceAsStream("TopBrands.xml");

If you get a Null Value Exception, try this (with class TopBrandData):

InputStream in_s1 =
    TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");
1
  • If not working , please Try this one : InputStream in_s1 = TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml"); Jul 2, 2014 at 8:25
3
InputStream is = getResources().getAssets().open("terms.txt");
String textfile = convertStreamToString(is);
    
public static String convertStreamToString(InputStream is)
        throws IOException {

    Writer writer = new StringWriter();
    char[] buffer = new char[2048];

    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        is.close();
    }

    String text = writer.toString();
    return text;
}
1

try this :

Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.cat); 

I had did it and it worked

2
  • 2
    Actually it works. Check ContentResolver.openAssetFileDescriptor Nov 14, 2016 at 17:20
  • 1
    Worked. Thanks a lot. Lol, I just looking for get URI internal file // CREATE RAW FOLDER INSIDE RES, THEN NAME FILE CONTAIN ONLY a..z0..9 character, NO UPPERCASE !!!
    – phnghue
    Apr 30, 2018 at 1:30
1

Since it's actually data in the APK file and not on the emulator, you won't be able to find an "absolute path". I've eventually implemented in this pretty straightforward way :

private fun getUriFromAsset(context: Context, assetFileName: String): Uri? {
    val assetManager = context.assets
    var inputStream: InputStream? = null
    var outputStream: FileOutputStream? = null
    var tempFile: File? = null

    return try {
        inputStream = assetManager.open(assetFileName)
        tempFile = File.createTempFile("temp_asset", null, context.cacheDir)
        outputStream = FileOutputStream(tempFile)

        inputStream.copyTo(outputStream)

        Uri.fromFile(tempFile)
    } catch (e: IOException) {
        e.printStackTrace()
        null
    } finally {
        inputStream?.close()
        outputStream?.close()
        tempFile?.deleteOnExit()
    }
}
0

Yeah you can't access your drive folder from you android phone or emulator because your computer and android are two different OS.I would go for res folder of android because it has good resources management methods. Until and unless you have very good reason to put you file in assets folder. Instead You can do this

try {
      Resources res = getResources();
      InputStream in_s = res.openRawResource(R.raw.yourfile);

      byte[] b = new byte[in_s.available()];
      in_s.read(b);
      String str = new String(b);
    } catch (Exception e) {
      Log.e(LOG_TAG, "File Reading Error", e);
 }
0

If you are okay with not using assets folder and want to get a URI without storing it in another directory, you can use res/raw directory and create a helper function to get the URI from resID:

internal fun Context.getResourceUri(@AnyRes resourceId: Int): Uri =
    Uri.Builder()
        .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
        .authority(packageName)
        .path(resourceId.toString())
        .build()

Now if you have a mydemo.txt file under res/raw directory you can simply get the URI by calling the above helper method

context.getResourceUri(R.raw.mydemo)

Reference: https://stackoverflow.com/a/57719958

-9

Worked for me Try this code

   uri = Uri.fromFile(new File("//assets/testdemo.txt"));
   String testfilepath = uri.getPath();
    File f = new File(testfilepath);
    if (f.exists() == true) {
    Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
    } else {
   Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();
 }
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.