- Assets (Активы)
- Чтение файлов
- Используем собственные шрифты
- Загрузка локальных файлов из активов в WebView
- Получаем список файлов в папке assets
- Ограничение на размер файлов
- Android: How to find the absolute path of the assets folder?
- 3 Answers 3
- How to get URI from an asset File?
- 11 Answers 11
- Android: How to detect a directory in the assets folder?
- 9 Answers 9
- Getting file path for local Android project files
- 3 Answers 3
Assets (Активы)
В Android имеется ещё один каталог, в котором могут храниться файлы, предназначенные для включения в пакет — assets. Этот каталог находится на том же уровне, что и res. Для файлов, располагающихся в assets, в R.java не генерируются идентификаторы ресурсов. Для их считывания необходимо указать путь к файлу. Путь к файлу является относительным и начинается с /assets. Этот каталог, в отличие от подкаталога res, позволяет задавать произвольную глубину подкаталогов и произвольные имена файлов и подкаталогов.
По умолчанию проект в студии не содержит данную папку. Чтобы её создать, выберите меню File | New | Folder | Assets Folder.
Чтение файлов
Для доступа к файлам используется класс AssetManager. Пример для чтения текстового файла.
Сначала на Kotlin.
Для доступа к графическому файлу из актива можно использовать следующий код:
Вы также можете загрузить изображение в Bitmap, используя BitmapFactory.decodeStream(), вместо Drawable.
Функция-расширение для Kotlin, которая вернёт Bitmap.
Используем собственные шрифты
Напишем практический пример создания приложения, в котором будут использоваться собственные шрифты, не входящие в стандартную библиотеку шрифтов Android. Для этого мы упакуем нужные шрифты вместе с приложением. Поместим в каталог assets/fonts файлы шрифтов (можно скачать бесплатные шрифты с сайтов 1001 Free Fonts или Urban Fonts ).
В файл разметки добавим пару текстовых полей с заготовленным текстом для вывода этого текста с нашим шрифтом.
В классе активности загрузим объект EditText из ресурсов, а затем создадим объект Typeface, используя вызов статического метода Typeface.createFromAsset(). Метод createFromAsset() принимает два параметра:
- объект AssetManager, который можно получить вызовом метода getAssets()
- путь к файлу актива.
Например, загрузить шрифт для текстового поля EditText можно следующим способом:
Запустив проект, мы увидим в текстовых полях надписи Happy New Year! и Meow!, выводимые нашими собственными шрифтами.
Пример для фрагмента.
Загрузка локальных файлов из активов в WebView
Если нужно загрузить локальные страницы и изображения из активов в WebView, то можно использовать префикс file://android_asset. Подробнее смотрите в статье про WebView.
Получаем список файлов в папке assets
Можно получить список файлов, которые находятся в папке assets. Для быстрой проверки кода я вручную скопировал в папку два файла:
Кроме ваших файлов, также возвращаются странные папки /images, /sounds, /webkit. Учитывайте это в своих проектах. Так как в папке можно создавать собственные подпапки, то можно воспользоваться вспомогательным методом:
Ограничение на размер файлов
По сети гуляет информация, что существует ограничение в 1 Мб на размер файлов в папке assets. При превышении размера у вас может появиться ошибка:
Я не сталкивался, поэтому рецепт решения проблемы не предлагаю.
Источник
Android: How to find the absolute path of the assets folder?
I need to get the absolute path of the assets folder in my app as I want to serve the files within using a webserver and it needs the absolute path. Is this possible?
I would have thought there might be something like this:
Any help appreciated, cheers.
3 Answers 3
No. There is no «absolute path of the assets folder in [your] app». Assets are stored in the APK file.
In select cases, such as URLs supplied to a WebView , you can use the special file:///android_asset base URL to reference files in your assets.
You can always copy files from the assets directory in the APK to a folder on the device, then serve that folder.
As mentioned, Android assets cannot be accessed with absolute paths in the device file system. So whenever you have to provide a filesystem path to a method, you’re out of luck.
However, in your case there are additional options:
I want to serve the files within using a webserver and it needs the absolute path.
Needing the absolute path is only true if you want to serve the file as a static file with the default mechanism a webserver provides for that. But webservers are much more flexible: you an map any path in an URL to any data source you can access: files, databases, web resources, Android resources, Android assets. How to do that depends on the web server you use.
Источник
How to get URI from an asset File?
I have been trying to get the URI path for an asset file.
When I check if the file exists I see that file doesn’t exist
Can some one tell me how I can mention the absolute path for a file existing in the asset folder
11 Answers 11
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.
The correct url is:
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.
Источник
Android: How to detect a directory in the assets folder?
I’m retrieving files like this
How can we know whether it is a file or is a directory?
I want to loop through the directories in the assets folder then copy all of its contents.
9 Answers 9
I think a more general solution (in case you have subfolders etc.) would be something like this (based on the solution you linked to, I’ve added it there too):
I’ve discovered this variant:
It’s a more faster as .list()
You may use list method of AssetManager. Any directory in asset should have one file at least, empty directory will be ignored when building your application. So, to determine if some path is directory, use like this:
The appalling truth is that despite being asked nearly 10 years ago, no simple, elegant, roundly applauded method of determining whether an element in the array returned by AssetManager.list() is a file or a directory has been offered by any answer to date.
So, for example, if an asset directory contains a thousand elements, then seemingly a thousand I/O operations are necessary to isolate the directories.
Nor, for any element, does any native method exist for obtaining its parent directory — vital for something complex like an assets Browser / Picker — where you could end up looking at some seriously ugly code.
The lateral approach that worked for me was to assume that any element without a dot (.) in its name was a directory. If the assumption is later proved wrong it can be easily rectified.
Asset files generally exist because you put them there. Deploy naming conventions that distinguish between directories and files.
Источник
Getting file path for local Android project files
I want to programmatically access a specific file which will be included in my project folder. Is there a way to do this? If so, where in my project folder do I put the file, and what is some simple code to get its file path?
3 Answers 3
Put the file in root folder of your project. Then get the File URL, Path and other details as:
EDIT: Alternate way (if the file is in your classpath e.g. put the file in «src» folder, and make sure its moved in «bin» or «classes» folder after compilation):
This depends a lot on what type of file you want to access. You can put the file in either assets or an appropriate subdirectory of res (see Difference between /res and /assets directories).
So you want to access a file internal to your app; and you want to do so directly, rather, that is, from an Android Context (and then with a [android.|
You have two choices as to location: the res/raw folder or assets/ folder (outside of the res parent).
Arbitrary files to save in their raw form. To open these resources with a raw InputStream , call Resources.openRawResource() with the resource ID, which is R.raw.filename .
However, if you need access to original file names and file hierarchy, you might consider saving some resources in the assets/ directory (instead of res/raw/ ). Files in assets/ aren’t given a resource ID, so you can read them only using AssetManager .
To access a file in res/raw/ directly rather, that is, from an Android Context (and then with a [android.|
Источник