- Assets (Активы)
- Чтение файлов
- Используем собственные шрифты
- Загрузка локальных файлов из активов в WebView
- Получаем список файлов в папке assets
- Ограничение на размер файлов
- Assets Folder in Android Studio
- How the asset folder is different from the Resource Raw folder?
- But when to use which folder?
- How to Create Assets Folder in Android Studio?
- Java – Чтение файла из папка ресурсов
- 1. Файлы в ресурсах папка
- 2. Получите файл из папки ресурсов.
- 3. Получите файл из папки ресурсов – Модульный тест
- 4. Получите все файлы из папки ресурсов. (Среда, ОТЛИЧНАЯ от JAR)
- 5. Получите все файлы из папки ресурсов. (Версия JAR)
- Что делает файл: / / / Android asset / www / index.HTML-код означает?
- 6 ответов
- Data and file storage overview
- Categories of storage locations
- Permissions and access to external storage
- Scoped storage
- View files on a device
- Additional resources
- Videos
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 Folder in Android Studio
It can be noticed that unlike Eclipse ADT (App Development Tools), Android Studio doesn’t contain an Assets folder in which we usually use to keep the web files like HTML. Assets provide a way to add arbitrary files like text, XML, HTML, fonts, music, and video in the application. If one tries to add these files as “resources“, Android will treat them into its resource system and you will be unable to get the raw data. If one wants to access data untouched, Assets are one way to do it. But the question arises is why in the asset folder? We can do the same things by creating a Resource Raw Folder. So let discuss how the assets folder is different from the Resource Raw folder?
How the asset folder is different from the Resource Raw folder?
In Android one can store the raw asset file like JSON, Text, mp3, HTML, pdf, etc in two possible locations:
- assets
- res/raw folder
Both of them appears to be the same, as they can read the file and generate InputStream as below
But when to use which folder?
Below is some guidance that might be helpful to choose
1. Flexible File Name: (assets is better)
- assets: The developer can name the file name in any way, like having capital letters (fileName) or having space (file name).
- res/raw: In this case, the name of the file is restricted. File-based resource names must contain only lowercase a-z, 0-9, or underscore.
2. Store in subdirectory: (possible in assets)
- assets: If the developer wants to categories the files into subfolders, then he/she can do it in assets like below.
3. Compile-time checking: (possible in res/raw)
- assets: Here, the way to read it into InputStream is given below. If the filename doesn’t exist, then we need to catch it.
- res/raw folder: Here, the way to read it into InputStream is:
So putting a file in the res/raw folder will provide ensure the correct file-name during compile time check.
4. List filenames at runtime: (possible in assets)
- assets: If the developer wants to list all the files in the assets folder, he/she has used the list() function and provide the folder name or ” “ on the root folder as given below.
- res/raw: This is not possible in this folder. The developer has to know the filename during development, and not runtime.
So, in assets, one can read the filename during runtime, list them, and use them dynamically. In res/raw, one needs to code them ready, perhaps in the string resources file.
5. Filename accessible from XML: (possible in res/raw)
So if you need to access your file in any XML, put it in the res/raw folder. Let’s make a table to remember the whole scenario easily.
Res/Raw Folder | |||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Flexible File Name NO | |||||||||||||||||||||||||||||||||||
Store in subdirectory NO | |||||||||||||||||||||||||||||||||||
Compile-time checking YES | |||||||||||||||||||||||||||||||||||
List filenames at runtime NO | |||||||||||||||||||||||||||||||||||
Filename accessible from XML How to Create Assets Folder in Android Studio?Now let’s discuss how to create an assets folder in the android studio. Below is the step-by-step process to create an assets folder in Android studio. Step 1: To create an asset folder in Android studio open your project in Android mode first as shown in the below image. Step 2: Go to the app > right-click > New > Folder > Asset Folder and create the asset folder. Step 3: Android Studio will open a dialog box. Keep all the settings default. Under the target source set, option main should be selected. and click on the finish button. Step 4: Now open the app folder and you will find the assets folder by the name of “assets” as shown in the below image. Источник Java – Чтение файла из папка ресурсовВ этой статье будет показано, как прочитать файл из папки “ресурсы”, “getResourceAsStream” или “getResource”. Автор: mkyong Автор оригинала: mkyong. В Java мы можем использовать getResourceAsStream или getResource для чтения файла или нескольких файлов из папки ресурсы или корневого каталога пути к классу. Метод getResourceAsStream возвращает Входной поток . Метод getResource возвращает URL и обычно преобразует его в Файл ; Не работает в файле JAR . 1. Файлы в ресурсах папка1.1 Просмотрите файлы в src/main/ресурсы , позже мы получим доступ к файлам и распечатаем содержимое файла. 1.2 По умолчанию инструменты сборки, такие как Maven, Gradle или обычная практика Java, будут копировать все файлы из src/основные/ресурсы в корневой каталог целевые/классы или сборка/классы . Итак, когда мы пытаемся прочитать файл из src/main/ресурсы , мы читаем файл из корневого каталога пути к классам проекта. 1.3 Ниже приведена структура файла JAR. Обычно файлы в папке ресурсы копируются в корневой каталог пути к классу. 2. Получите файл из папки ресурсов.2.1 Приведенный ниже пример демонстрирует использование getResourceAsStream и getResource методы чтения файла json/файл 1.json из папки ресурсы
2.2 Теперь мы упаковываем проект в файл JAR и запускаем его; на этот раз getResource завершится ошибкой и вернет либо Исключение NoSuchFileException , либо Исключение InvalidPathException . Мы не можем прочитать файлы внутри файла JAR по URL-адресу ресурса. Запустите файл JAR в Linux (Ubuntu), он вызовет Исключение NoSuchFileException . Запустите файл JAR в Windows, он вызовет Исключение InvalidPathException . P.S В этом примере используется плагин Maven maven-jar-плагин чтобы создать файл JAR. 3. Получите файл из папки ресурсов – Модульный тест3.1 Мы помещаем тестовые ресурсы в папку src/test/ресурсы для модульных тестов. Обычно файлы в тестовых ресурсах копируются в папку target/test-classes . 3.2 Это работает так же, как мы читаем файл из src/main/ресурсы . Мы используем то же самое getResourceAsStream и getResource методы чтения файла из src/test/ресурсов . 4. Получите все файлы из папки ресурсов. (Среда, ОТЛИЧНАЯ от JAR)Если мы не знаем точного имени файла и хотим прочитать все файлы, включая файлы вложенных папок из папки ресурсов, мы можем использовать NIO Файлы.перейдите , чтобы легко получить доступ к файлам и прочитать их. 4.1 В приведенном ниже примере используются Файлы.пройдите чтобы прочитать все файлы из папки src/основные/ресурсы/json : 4.2 Однако стандартные Файлы.прогулка в примере 4.1 не удается получить доступ к файлам в файле JAR напрямую, попробуйте запустить пример 4.1 в среде JAR, и он выдает Исключение FileSystemNotFoundException . 5. Получите все файлы из папки ресурсов. (Версия JAR)5.1 В этом примере показано, как Файлы.перейдите в папку внутри файла JAR через Файловые системы и URI jar:файл: xxx.jar . Идея в том, чтобы:
Источник Что делает файл: / / / Android asset / www / index.HTML-код означает?Я хочу знать, что значит file:/// означает При загрузке html-файла из папки assets в android это абсолютное имя пути, которое указывает на корневой каталог? Я видел это в учебнике для phonegap, кстати. 6 ответовfile:/// — это URI (Uniform Resource Identifier), который просто отличается от стандартного URI, который мы все знаем слишком хорошо — http:// . это означает абсолютное имя пути, указывающее на корневой каталог в любой среде, но в контексте Android это соглашение, чтобы сказать Android run-time сказать»здесь каталог www есть файл под названием index.html расположенном в Если кто-то использует AndroidStudio, убедитесь, что папка assets помещена в app/src/main / активы URI-код «file:///android_asset/» указывает на YourProject/app/src/main/assets/ . Примечание: android_asset/ использует единственное число (актив) и src/main/assets использует множественное (активов). Предположим, у вас есть файл YourProject/app/src/main/assets/web_thing.html что вы хотели бы отобразить в WebView. Вы можете обратиться к нему так: код выше может быть расположен в папке активность класс, возможно, в onCreate метод. здесь руководство общий структура каталогов проекта android, которая помогла мне понять этот ответ. это на самом деле называется file:///android_asset/index.html file:///android_assets/index.html даст вам ошибку построения. считайте отредактировать заголовок вопрос
Я использую Android Studio (Eclipse с ADT не может работать должным образом из-за проблемы сборки). Источник Data and file storage overviewAndroid uses a file system that’s similar to disk-based file systems on other platforms. The system provides several options for you to save your app data:
The characteristics of these options are summarized in the following table:
The solution you choose depends on your specific needs: How much space does your data require? Internal storage has limited space for app-specific data. Use other types of storage if you need to save a substantial amount of data. How reliable does data access need to be? If your app’s basic functionality requires certain data, such as when your app is starting up, place the data within internal storage directory or a database. App-specific files that are stored in external storage aren’t always accessible because some devices allow users to remove a physical device that corresponds to external storage. What kind of data do you need to store? If you have data that’s only meaningful for your app, use app-specific storage. For shareable media content, use shared storage so that other apps can access the content. For structured data, use either preferences (for key-value data) or a database (for data that contains more than 2 columns). Should the data be private to your app? When storing sensitive data—data that shouldn’t be accessible from any other app—use internal storage, preferences, or a database. Internal storage has the added benefit of the data being hidden from users. Categories of storage locationsAndroid provides two types of physical storage locations: internal storage and external storage. On most devices, internal storage is smaller than external storage. However, internal storage is always available on all devices, making it a more reliable place to put data on which your app depends. Removable volumes, such as an SD card, appear in the file system as part of external storage. Android represents these devices using a path, such as /sdcard . Apps themselves are stored within internal storage by default. If your APK size is very large, however, you can indicate a preference within your app’s manifest file to install your app on external storage instead: Permissions and access to external storageOn earlier versions of Android, apps needed to declare the READ_EXTERNAL_STORAGE permission to access any file outside the app-specific directories on external storage. Also, apps needed to declare the WRITE_EXTERNAL_STORAGE permission to write to any file outside the app-specific directory. More recent versions of Android rely more on a file’s purpose than its location for determining an app’s ability to access, and write to, a given file. In particular, if your app targets Android 11 (API level 30) or higher, the WRITE_EXTERNAL_STORAGE permission doesn’t have any effect on your app’s access to storage. This purpose-based storage model improves user privacy because apps are given access only to the areas of the device’s file system that they actually use. Android 11 introduces the MANAGE_EXTERNAL_STORAGE permission, which provides write access to files outside the app-specific directory and MediaStore . To learn more about this permission, and why most apps don’t need to declare it to fulfill their use cases, see the guide on how to manage all files on a storage device. Scoped storageTo give users more control over their files and to limit file clutter, apps that target Android 10 (API level 29) and higher are given scoped access into external storage, or scoped storage, by default. Such apps have access only to the app-specific directory on external storage, as well as specific types of media that the app has created. Use scoped storage unless your app needs access to a file that’s stored outside of an app-specific directory and outside of a directory that the MediaStore APIs can access. If you store app-specific files on external storage, you can make it easier to adopt scoped storage by placing these files in an app-specific directory on external storage. That way, your app maintains access to these files when scoped storage is enabled. To prepare your app for scoped storage, view the storage use cases and best practices guide. If your app has another use case that isn’t covered by scoped storage, file a feature request. You can temporarily opt-out of using scoped storage. View files on a deviceTo view the files stored on a device, use Android Studio’s Device File Explorer. Additional resourcesFor more information about data storage, consult the following resources. VideosContent and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates. Источник |