Get all files assets android

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. При превышении размера у вас может появиться ошибка:

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

Источник

Помещаем файлы из Assets на SD-карту с помощью Infles

Доброго времени суток, Хабравчане!

Описание:

Почти все пользователи ОС Android знают практику приложений использовать файлы с SD карты.
Большинство приложений скачивают с интернета эти файлы и помещают их в свою папку, но не у всех пользователей есть возможность скачивать их из сети и не у всех разработчиков содержать свой сервер, а вручную копировать файлы, согласитесь, неудобно.
Поэтому что бы упростить всем жизнь и была написана программа «Infles», она распространяется бесплатно с открытым исходным кодом и по лицензии MIT. Программа позволяет в 1 клик установить необходимые файлы в указанную в настройках папку на SD карте. Для этого необходимо поместить их в папку «assets», в коде в файле «\Infles\src\ru\boomik\infles\InflesActivity.java» в переменной «COPY_DIR» указать путь на карте памяти и скомпилировать программу.

Идея программы появилась как раз при использовании приложения, для доступа ко всем возможностям которого необходимо было скопировать файлы на флэшку в определенную папку, а встроенного механизма небыло.

А теперь о создании и коде.

Приложение получилось простым, да и это его цель — простота и удобство использования. Состоит всего из 2-х классов, активити и сервис (для большей стабильности). Сервис ничего толкового не имеет, а вот активити разберем, в нем как раз и содержатся все функции (в конце статьи предоставлю ссылки на исходный код и пример приложения).
Layout (слой) приложения содержит 4 кнопки — одна большая, почти на весь экран и 3 дополнительных (которые можно скрыть изменив значение SHOW_BUTTON на false).
Активити содержит ряд функций, которые будут рассмотрены ниже.
Код не сложный, но объясню все по пунктам. Куски кода будут идти по очереди, как они расположены в самом классе.

Читайте также:  Disable html5 autoplay opera android

Выполняем необходимые импорты, объявляем класс «InflesActivity» и переменные необходимые для работы программы, а под ними настройки.

boolean SHOW_BUTTON = true; — отображать дополнительные кнопки на экране;
boolean UNZIP = false; — распаковывать zip архивы;
boolean DEL_ZIP = false; — удалять zip архивы (только при включенной опции распаковки);
String COPY_DIR = «Infles»; — путь на SD карте. «/» в начале и конце не ставить.

В функции «onCreate» сперва определяются все кнопки («ActButton», «Delete», «About», «Exit»), затем присваиваются кнопкам Listener’ы и идет проверка переменной «SHOW_BUTTON» и если она ложна, тогда кнопки скрываются.

Обработчик нажатия на кнопку «RUN!». Сначала вызывается диалог прогресса (код дальше), далее объявляются новые переменные для использования в программе. После этого в новом потоке читаются все файлы из папки «Assets», для чего была объявлена переменная «am» типа «AssetManager». Далее функцией «CheckMass()» проверяем, нет ли файла в черном списке названий (почему-то при считывании папки Assets находятся левые папки, причину пока не выяснил, но отсеиваю их), функцией «dirChecker()» проверяется существование папки, и если такой нет, то создается, и после происходит собственно копирование файлов функцией «copy()». Следующий участок кода проверяет, включена ли опция извлечения архивов, и если да, тогда проверяются файлы по расширению, и если находит, извлекает из в текущаю папку (функция «Unzip()»). Архив может содержать подпапки, что демонстрируется в примере, если просто в папке Assets будет подпапка-она не скопируется, буду искать решение. Далее происходит закрытие диалога, потока, программы и вызывается диалог удаления программы — её функция выполнилась и хранить её не имеет смысла, хотя можно нажать Отмена и она останется.

Тут выполняются листенеры остальных трех дополнительных кнопок, которые вызывают свои функции. Функция showDialog(ABOUT) вызывает диалог About (О программе), функция Exit() закрывает активити и останавливает сервис, а функция DeleteApp() открывает диалог деинсталяции приложения.

Эта функция вызывается при открытии диалога «О программе» и прогресс-диалога. Функции передается переменная типа «int» и основываясь на неё вызывается соответствующий диалог. Сами диалоги описывать ну буду — по ним в интернете уже очень много статей, и плюс на developer.android.com есть пример хороший. Скажу только, что для окна «О программе» используется свой xml лэйаут и текст выводится из кода и выводится в виде html кода, для поддержки ссылок.

Это главная функция программы-копирование файлов, да и тут нет ничего предельно сложного, в переменной destinationFile появляется ссылка на файл, потом открывается файл и копируется чустями по 1 кб.

Функция извлечения зип архивов. Тут используется стандартная функция языка Java для работы с архивами.

Две маленьких функции проверки создания папки, если такой нету и поиск значения переменной по массиву, для черного списка файлов.

Ну а тут выводится меню, которое вызывается, как можно догадаться — по хард-енопке «Menu» на любом Андроид-девайсе.

Файлы layout’ов и меню простейшие, поэтому приводить их в статье не буду — кому интересно прошу на SVN на просмотр кода и изучения примера.

Если есть какие пожелания для программы, или предложения, как улучшить код — пишите, постараюсь реализовать.
Еще раз напоминаю, что программа абсолютно бесплатная, можете использовать с воих проектах без ограничений, но желательно оставить оригинальное название и окно «О программе».

Сложности

Первая сложность была связана с адресами путей, в разных местах пришлось по разному описывать их.
Вторая заключалась в невозможности создать подпапки, решил введением извлечения из архива.
Третья — не возможность задать русское название файла или папки. Пока не решил, да и стоит ли?
Четвертая проблема не знаю откуда появилась и как — скрытые файлы без расширения в папке Assets, для которых применяется фильтр.

Источник

Saving Files

This lesson teaches you to

You should also read

Android uses a file system that’s similar to disk-based file systems on other platforms. This lesson describes how to work with the Android file system to read and write files with the File APIs.

A File object is suited to reading or writing large amounts of data in start-to-finish order without skipping around. For example, it’s good for image files or anything exchanged over a network.

This lesson shows how to perform basic file-related tasks in your app. The lesson assumes that you are familiar with the basics of the Linux file system and the standard file input/output APIs in java.io .

Choose Internal or External Storage

All Android devices have two file storage areas: «internal» and «external» storage. These names come from the early days of Android, when most devices offered built-in non-volatile memory (internal storage), plus a removable storage medium such as a micro SD card (external storage). Some devices divide the permanent storage space into «internal» and «external» partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not. The following lists summarize the facts about each storage space.

  • It’s always available.
  • Files saved here are accessible by only your app by default.
  • When the user uninstalls your app, the system removes all your app’s files from internal storage.
Читайте также:  Outlook calendar with android

Internal storage is best when you want to be sure that neither the user nor other apps can access your files.

  • It’s not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device.
  • It’s world-readable, so files saved here may be read outside of your control.
  • When the user uninstalls your app, the system removes your app’s files from here only if you save them in the directory from getExternalFilesDir() .

External storage is the best place for files that don’t require access restrictions and for files that you want to share with other apps or allow the user to access with a computer.

Tip: Although apps are installed onto the internal storage by default, you can specify the android:installLocation attribute in your manifest so your app may be installed on external storage. Users appreciate this option when the APK size is very large and they have an external storage space that’s larger than the internal storage. For more information, see App Install Location.

Obtain Permissions for External Storage

To write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:

Caution: Currently, all apps have the ability to read the external storage without a special permission. However, this will change in a future release. If your app needs to read the external storage (but not write to it), then you will need to declare the READ_EXTERNAL_STORAGE permission. To ensure that your app continues to work as expected, you should declare this permission now, before the change takes effect.

However, if your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.

You don’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory.

Save a File on Internal Storage

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir() Returns a File representing an internal directory for your app. getCacheDir() Returns a File representing an internal directory for your app’s temporary cache files. Be sure to delete each file once it is no longer needed and implement a reasonable size limit for the amount of memory you use at any given time, such as 1MB. If the system begins running low on storage, it may delete your cache files without warning.

To create a new file in one of these directories, you can use the File() constructor, passing the File provided by one of the above methods that specifies your internal storage directory. For example:

Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here’s how to write some text to a file:

Or, if you need to cache some files, you should instead use createTempFile() . For example, the following method extracts the file name from a URL and creates a file with that name in your app’s internal cache directory:

Note: Your app’s internal storage directory is specified by your app’s package name in a special location of the Android file system. Technically, another app can read your internal files if you set the file mode to be readable. However, the other app would also need to know your app package name and file names. Other apps cannot browse your internal directories and do not have read or write access unless you explicitly set the files to be readable or writable. So as long as you use MODE_PRIVATE for your files on the internal storage, they are never accessible to other apps.

Save a File on External Storage

Because the external storage may be unavailable—such as when the user has mounted the storage to a PC or has removed the SD card that provides the external storage—you should always verify that the volume is available before accessing it. You can query the external storage state by calling getExternalStorageState() . If the returned state is equal to MEDIA_MOUNTED , then you can read and write your files. For example, the following methods are useful to determine the storage availability:

Читайте также:  Как синхронизировать китайские часы с телефоном андроид

Although the external storage is modifiable by the user and other apps, there are two categories of files you might save here:

Public files Files that should be freely available to other apps and to the user. When the user uninstalls your app, these files should remain available to the user.

For example, photos captured by your app or other downloaded files.

Private files Files that rightfully belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, they are files that realistically don’t provide value to the user outside your app. When the user uninstalls your app, the system deletes all files in your app’s external private directory.

For example, additional resources downloaded by your app or temporary media files.

If you want to save public files on the external storage, use the getExternalStoragePublicDirectory() method to get a File representing the appropriate directory on the external storage. The method takes an argument specifying the type of file you want to save so that they can be logically organized with other public files, such as DIRECTORY_MUSIC or DIRECTORY_PICTURES . For example:

If you want to save files that are private to your app, you can acquire the appropriate directory by calling getExternalFilesDir() and passing it a name indicating the type of directory you’d like. Each directory created this way is added to a parent directory that encapsulates all your app’s external storage files, which the system deletes when the user uninstalls your app.

For example, here’s a method you can use to create a directory for an individual photo album:

If none of the pre-defined sub-directory names suit your files, you can instead call getExternalFilesDir() and pass null . This returns the root directory for your app’s private directory on the external storage.

Remember that getExternalFilesDir() creates a directory inside a directory that is deleted when the user uninstalls your app. If the files you’re saving should remain available after the user uninstalls your app—such as when your app is a camera and the user will want to keep the photos—you should instead use getExternalStoragePublicDirectory() .

Regardless of whether you use getExternalStoragePublicDirectory() for files that are shared or getExternalFilesDir() for files that are private to your app, it’s important that you use directory names provided by API constants like DIRECTORY_PICTURES . These directory names ensure that the files are treated properly by the system. For instance, files saved in DIRECTORY_RINGTONES are categorized by the system media scanner as ringtones instead of music.

Query Free Space

If you know ahead of time how much data you’re saving, you can find out whether sufficient space is available without causing an IOException by calling getFreeSpace() or getTotalSpace() . These methods provide the current available space and the total space in the storage volume, respectively. This information is also useful to avoid filling the storage volume above a certain threshold.

However, the system does not guarantee that you can write as many bytes as are indicated by getFreeSpace() . If the number returned is a few MB more than the size of the data you want to save, or if the file system is less than 90% full, then it’s probably safe to proceed. Otherwise, you probably shouldn’t write to storage.

Note: You aren’t required to check the amount of available space before you save your file. You can instead try writing the file right away, then catch an IOException if one occurs. You may need to do this if you don’t know exactly how much space you need. For example, if you change the file’s encoding before you save it by converting a PNG image to JPEG, you won’t know the file’s size beforehand.

Delete a File

You should always delete files that you no longer need. The most straightforward way to delete a file is to have the opened file reference call delete() on itself.

If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling deleteFile() :

Note: When the user uninstalls your app, the Android system deletes the following:

  • All files you saved on internal storage
  • All files you saved on external storage using getExternalFilesDir() .

However, you should manually delete all cached files created with getCacheDir() on a regular basis and also regularly delete other files you no longer need.

Источник

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