- Android: List External Storage Files
- Как вывести список файлов в каталоге Android?
- Создание удобного OpenFileDialog для Android
- Saving Files
- This lesson teaches you to
- You should also read
- Choose Internal or External Storage
- Obtain Permissions for External Storage
- Save a File on Internal Storage
- Save a File on External Storage
- Query Free Space
- Delete a File
Android: List External Storage Files
As you can see, the TextView is wrapped in a ScrollView to handle a large number of files.
Step 4:
Open the MainActivity.kt and add a listFiles and a listExternalStorage function as shown below:
The listFiles receives a directory and recursively list files in that directory. If the newly found File is a directory, it’s sub-files are listed recursively. If it is an actual file, the absolute path of that file is appended to the txtFiles TextView .
Step 5:
Add the requestCode variable, the list function and override the onRequestPermissionsResult function as shown below:
Step 6:
Add the rxjava dependency to the build.gradle (Module: app) .
After adding these two dependencies your build.gradle should look like this:
After saving the changes, synchronize the project to download the dependencies.
Step 7:
Modify the MainActivity.kt as shown below:
Notice that there is a disposable instance variable which is used to dispose the RxJava resources in the onPause method and in the onComplete (the third block in the subscribe method call) lambda expression. Now there is a FileLister publisher which receives the parent directory to traverse and publish the files to the subscriber. Once the traversal is completed (after the recursive method call), the publisher calls the onComplete method to let the subscriber know that the process is completed.
The listExternalStorage function executes the publisher in a separate thread and appends the result to TextView in the main thread.
Though we can list all the files from the external storage, it is not recommended to do so unless otherwise there is a valid reason behind it. You can find the source code of this project at the GitHub repository.
If you have any questions, feel free to comment below.
Источник
Как вывести список файлов в каталоге Android?
Тем не менее, хотя у меня есть файлы в этом каталоге, он возвращает мне list.length = 0 . какие-нибудь идеи?
Чтобы получить доступ к файлам, разрешения должны быть указаны в файле манифеста.
Я только что обнаружил, что:
new File(«/sdcard/»).listFiles() возвращает null, если у вас нет:
установить в вашем файле AndroidManifest.xml.
Ну, AssetManager списки файлов в assets папке, которая находится внутри вашего файла APK. Итак, в приведенном выше примере вы пытаетесь указать [apk] / assets / sdcard / Pictures.
Если вы поместите несколько изображений в assets папку внутри вашего приложения, и они будут в Pictures каталоге, вы сделаете mgr.list(«/Pictures/») .
С другой стороны, если у вас есть файлы на SD-карте, которые находятся за пределами вашего файла APK, в Pictures папке, вы должны использовать File так:
И соответствующие ссылки из документов:
File
Asset Manager
В дополнение ко всем приведенным выше ответам:
Если вы используете Android 6.0+ (уровень API 23+), вы должны явно запросить разрешение на доступ к внешнему хранилищу. Просто имея
в вашем манифесте будет недостаточно. Вы также активно запрашивали разрешение в своей деятельности:
Ваш path не находится в папке с ресурсами. Вы либо перечисляете файлы в папке с активами с помощью, AssetManager.list() либо перечисляете файлы на SD-карте с помощью File.list()
Могут произойти две вещи:
- Вы не добавляете READ_EXTERNAL_STORAGE разрешение на AndroidManifest.xml
- Вы ориентируетесь на Android 23 и не запрашиваете у пользователя это разрешение. Перейдите на Android 22 или спросите у пользователя разрешение.
Если вы используете Android 10 / Q и сделали все правильно, чтобы запросить разрешения на доступ для чтения внешнего хранилища, но оно по-прежнему не работает, стоит прочитать этот ответ:
У меня был рабочий код, но мое устройство взяло на себя обновление, когда оно было подключено к сети (обычно оно было без подключения). В Android 10 доступ к файлам больше не работал. Единственный простой способ исправить это, не переписывая код, — это добавить этот дополнительный атрибут в манифест, как описано. Доступ к файлам теперь снова работает как в Android 9. YMMV, вероятно, он не будет работать в будущих версиях.
Источник
Создание удобного OpenFileDialog для Android
Наверное, как и многие разработчики под Android, столкнулся на днях с необходимостью реализовать в своем приложении выбор файла пользователем. Так как изначально в Android такого функционала нет, обратился к великому и ужасному. Это показалось мне странным, но из вороха вопросов на stackoverflow и небольшого числа отечественных форумов можно выделить всего три основных источника:
- Android File Dialog – почти все ссылки из stackoverflow ведут сюда. В принципе, неплохое решение, но реализовано через отдельную activity, а хотелось чего-то в духе OpenFileDialog’а из .Net.
- В данной статье речь идет вообще об отдельном файл-менеджере, и почерпнуть какие-то идеи из неё не удалось.
- Идея же отсюда очень понравилась, однако, как мне показалось реализовать все это можно несколько красивее.
В результате, начав реализовывать своё решение, я столкнулся с некоторыми трудностями решать которые показалось очень интересно. А посему, решил описать в данной статье не просто готовое решение, а все шаги, которые к нему привели. Желающие пройти их вместе –
Итак, приступим! В любой привычной среде (я использую IntelliJ IDEA) создадим новое приложение. На главной activity расположим одну единственную кнопку и напишем к ней, пока пустой, обработчик нажатия:
Создадим новый класс с конструктором:
а в обработчике кнопки вызовем диалог:
Кнопки показались, теперь надо бы и сами файлы найти. Начнем поиск с корня sdcard, для чего определим поле:
и реализуем следующий метод:
(так как главное требование к классу – работать сразу у любого разработчика, без подключения дополнительных библиотек, — то никаких google-collections использовать не будем, и с массивами приходится работать по старинке), а в конструкторе к вызову setNegativeButton добавим .setItems(getFiles(currentPath), null).
Что же, неплохо, однако файлы не отсортированы. Реализуем для этого дела Adapter как внутренний класс, заменим setItems на setAdapter и немного перепишем getFiles:
Еще лучше, но нам надо по клику на папке идти внутрь. Можно достучаться до встроенного listview, но я просто подменил его собственным (это потом пригодится). Плюс, изменения adapter’а внутри обработчика listview вызывало exception, и список файлов пришлось вынести в отдельное поле:
Отлично, вот только нажав на папку Android мы получаем список всего из одного каталога data, и наше окно тут же уменьшается в размере.
Возможно это нормально, но мне это не понравилось, и я стал искать возможности размер сохранить. Единственный найденный мною вариант – это установка setMinimumHeight. Установка этого свойства для listview вызвала дополнительные проблемы, но они решились оберткой его в LinearLayout:
Результат, все равно получился немного не таким, каким хотелось бы: при старте диалог развернут на весь экран, а после перехода в каталог Android – уменьшается до 750px. Да еще и экраны разных устройств имеют разную высоту. Решим сразу обе этих проблемы, установив setMinimumHeight в максимально возможную для текущего экрана:
Не нужно пугаться того, что мы устанавливаем в setMinimumHeight полный размер экрана, сама система уменьшит значение до максимально допустимого.
Теперь появляется проблема понимания пользователя, в каком каталоге он сейчас находится, и возврата вверх. Давайте разберемся с первой. Вроде все легко — установить значение title в currentPath и менять его при изменении последнего. Добавим в конструктор и в метод RebuildFiles вызов setTitle(currentPath).
А нет – заголовок не изменился. Почему не срабатывает setTitle после показа диалога, документация молчит. Однако мы может это исправить, создав свой заголовок и подменив им стандартный:
И снова не все ладно: если пройти достаточно далеко, то строка в заголовок влезать не будет
Решение с установкой setMaximumWidth не верно, так как пользователь будет видеть только начало длинного пути. Не знаю, насколько верно мое решение, но я сделал так:
Решим теперь проблему с возвратом. Это достаточно легко, учитывая, что у нас есть LinearLayout. Добавим в него еще один TextView и немного отрефракторим код:
Возможность возвращаться на шаг вверх, может привести пользователя в каталоги, к которым ему доступ запрещен, поэтому изменим функцию RebuildFiles:
(cообщение пока не очень информативное, но вскоре мы добавим разработчику возможность исправить это).
Ни один OpenFileDialog не обходится без фильтра. Добавим и его:
Обратите внимание — фильтр принимает регулярное выражение. Казалось бы – все хорошо, но первая выборка файлов сработает в конструкторе, до присвоения фильтра. Перенесем её в переопределенный метод show:
Осталось совсем чуть-чуть: вернуть выбранный файл. Опять же, я так и не понял зачем нужно устанавливать CHOICE_MODE_SINGLE, а потом все равно писать лишний код для подсветки выбранного элемента, когда он (код) и так будет работать без CHOICE_MODE_SINGLE, а потому обойдемся без него:
Источник
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.
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.
Источник