Android reading asset files

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.

Читайте также:  Карты навигатор 7 дорог для андроид с картами

Получаем список файлов в папке assets

Можно получить список файлов, которые находятся в папке assets. Для быстрой проверки кода я вручную скопировал в папку два файла:

Кроме ваших файлов, также возвращаются странные папки /images, /sounds, /webkit. Учитывайте это в своих проектах. Так как в папке можно создавать собственные подпапки, то можно воспользоваться вспомогательным методом:

Ограничение на размер файлов

По сети гуляет информация, что существует ограничение в 1 Мб на размер файлов в папке assets. При превышении размера у вас может появиться ошибка:

Я не сталкивался, поэтому рецепт решения проблемы не предлагаю.

Источник

Using Android Assets

Assets provide a way to include arbitrary files like text, xml, fonts, music, and video in your application. If you try to include these files as «resources», Android will process them into its resource system and you will not be able to get the raw data. If you want to access data untouched, Assets are one way to do it.

Assets added to your project will show up just like a file system that can read from by your application using AssetManager. In this simple demo, we are going to add a text file asset to our project, read it using AssetManager , and display it in a TextView.

Add Asset to Project

Assets go in the Assets folder of your project. Add a new text file to this folder called read_asset.txt . Place some text in it like «I came from an asset!».

Visual Studio should have set the Build Action for this file to AndroidAsset:

Visual Studio for Mac should have set the Build Action for this file to AndroidAsset:

Selecting the correct BuildAction ensures that the file will be packaged into the APK at compile time.

Reading Assets

Assets are read using an AssetManager. An instance of the AssetManager is available by accessing the Assets property on an Android.Content.Context , such as an Activity. In the following code, we open our read_asset.txt asset, read the contents, and display it using a TextView.

Reading Binary Assets

The use of StreamReader in the above example is ideal for text assets. For binary assets, use the following code:

Running the Application

Run the application and you should see the following:

Источник

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.

Источник

read file from assets

I am using this code trying to read a file from assets. I tried two ways to do this. First, when use File I received FileNotFoundException , when using AssetManager getAssets() method isn’t recognized. Is there any solution here?

18 Answers 18

Here is what I do in an activity for buffered reading extend/modify to match your needs

EDIT : My answer is perhaps useless if your question is on how to do it outside of an activity. If your question is simply how to read a file from asset then the answer is above.

UPDATE :

To open a file specifying the type simply add the type in the InputStreamReader call as follow.

EDIT

As @Stan says in the comment, the code I am giving is not summing up lines. mLine is replaced every pass. That’s why I wrote //process line . I assume the file contains some sort of data (i.e a contact list) and each line should be processed separately.

Читайте также:  Оплата покупок с помощью андроид

In case you simply want to load the file without any kind of processing you will have to sum up mLine at each pass using StringBuilder() and appending each pass.

ANOTHER EDIT

According to the comment of @Vincent I added the finally block.

Also note that in Java 7 and upper you can use try-with-resources to use the AutoCloseable and Closeable features of recent Java.

CONTEXT

In a comment @LunarWatcher points out that getAssets() is a class in context . So, if you call it outside of an activity you need to refer to it and pass the context instance to the activity.

This is explained in the answer of @Maneesh. So if this is useful to you upvote his answer because that’s him who pointed that out.

Источник

Использование ресурсов Android

Ресурсы предоставляют возможность включать в приложение произвольные файлы, такие как текст, XML, шрифты, музыка и видео. Если вы попытаетесь включить эти файлы как «Resources», Android обработает их в своей системе ресурсов и вы не сможете получить необработанные данные. Если вы хотите получить доступ к данным без вмешательства пользователя, ресурсы являются одним из способов сделать это.

Ресурсы, добавленные в проект, будут отображаться так же, как файловая система, способная выполнять чтение из приложения с помощью ассетманажер. В этой простой демонстрации мы добавим к нашему проекту ресурс текстового файла, прочесть его с помощью AssetManager и отобразить в TextView.

Добавить ресурс в Project

Ресурсы находятся в Assets папке проекта. Добавьте в эту папку новый текстовый файл с именем read_asset.txt . Поместите в него некоторый текст, например «я пришел от ресурса!».

Visual Studio должен задать для этого файла действие сборкиAndroidAsset:

Visual Studio для Mac должен задать для этого файла действие сборкиAndroidAsset:

Если выбрать правильное действие , это гарантирует, что файл будет УПАКОВАН в APK во время компиляции.

Чтение ресурсов

Ресурсы считываются с помощью ассетманажер. Экземпляр объекта AssetManager доступен при доступе к свойству AssetManager в Android.Content.Context , такому как действие. В следующем коде мы откроем наш ресурс read_asset.txt , прочтите его содержимое и отобразите с помощью TextView.

Чтение двоичных ресурсов

Использование StreamReader в приведенном выше примере идеально подходит для текстовых ресурсов. Для двоичных ресурсов используйте следующий код:

Запуск приложения

Запустите приложение, и вы должны увидеть следующее:

Источник

Оцените статью