Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to open file as File object from android's assets folder?

I would like to get the filesize of a file located in the assets directory. I saw many examples like

 InputStream myInput = appContext.getAssets().open() 

I know i can determine filesize by simple reading InputStream in cycle but I'm looking for a way to do this via File object.
So i need a path to assets and thats the thing i can't determine... How to get that path?
Also tried getting AssetFileDescriptor via appContext.getAssets().openFd() and openNonAssetFd() but no luck - got FileNotFound or probably compressed exceptions.
BTW those openFd methods are "pretty described" at developer.android.com.


I'd tried next code:
file = new File(new URI("file:///android_asset/db/call3.db"));
Log.i(APP_TAG, "File name: "+file.getName());
Log.i(APP_TAG, "File path: "+file.getPath());
Log.i(APP_TAG, "File length: "+file.length());
Log.i(APP_TAG, "File isFile: "+file.isFile());
Log.i(APP_TAG, "File exists: "+file.exists());

which outputs to log:
04-13 12:10:03.413: INFO(6259): File name: call3.db
04-13 12:10:03.432: INFO(6259): File path: /android_asset/db/call3.db
04-13 12:10:03.444: INFO(6259): File length: 0
04-13 12:10:03.444: INFO(6259): File isFile: false
04-13 12:10:03.444: INFO(6259): File exists: false

of course the size of file is not 0 it is 195 584 bytes.

like image 615
Stan Avatar asked Apr 13 '11 09:04

Stan


People also ask

How do I access asset files on Android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 – Right click app >> New >> Folder >> Assets folder.

How do I open an assets folder?

You can open assets folder in Visual Studio Code by simply right-clicking it in Solution Explorer and select Open Assets in VS Code. On default, extension looks for [anyname]. assets folder in solution folder. If it finds, it will run VS Code in that directory.

How do I read a file from assets folder in flutter?

Create an assets folder in your project's root folder. In Android Studio you can right click the Project outline and go to New > Directory. You can create another subfolder for text files in assets if you like. But if you do, you have to include the relative path in pubspec.


2 Answers

How to get that path?

There is no path. What you are seeking is not possible, sorry.

like image 107
CommonsWare Avatar answered Nov 08 '22 06:11

CommonsWare


I am not sure if there is any way to get a File object from an assets folder but to find out the length of a file in single line, you can use the following code.

AssetFileDescriptor afd = context.getAssets().openFd(fileName);
long size = afd.getLength();
like image 40
Keshav Bansal Avatar answered Nov 08 '22 06:11

Keshav Bansal