- Android: List External Storage Files
- Как вывести список файлов в каталоге Android?
- Java: List Files in a Directory
- Introduction
- File.list()
- FilenameFilter
- File.listFiles()
- Files.walk()
- Free eBook: Git Essentials
- Conclusion
- List files with Cloud Storage on Android
- List all files
- Kotlin+KTX
- Paginate list results
- Kotlin+KTX
- Handle errors
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, вероятно, он не будет работать в будущих версиях.
Источник
Java: List Files in a Directory
Introduction
A lot of applications handle files in some way and file manipulation is one of the core knowledges in any programming language.
In order to manipulate files, we need to know where they’re located. Having an overview of files in a directory is paramount if we want to accomplish this, especially if we can perform operations on them through iteration. There are several ways to do this in Java, which we’ll show throughout this article.
For the sake of simplicity, all examples will be written for the following file tree:
File.list()
The simplest method to list the names of files and folders in a given directory, without traversing the sub-directories, is the helper method .list() , which returns an array of String s.
We do this by using the .list() method on a File instance:
Using a simple for-each loop, we iterate through the array and print out the String s.
Using this approach, all of the items in the CodingMusic directory aren’t shown, and a downside to this approach is that we can’t really do anything to the files themselves. We’re just getting their names. It’s useful when we just want to take a look at the files at face-value.
FilenameFilter
Another thing we can do with the .list() method is to create a FilenameFilter to return only the files we want:
Running this piece of code would yield:
File.listFiles()
Similar to the previous method, this one can be used to return the names of files and directories, but this time we get them as an array of File objects, which gives us the ability to directly manipulate them:
Now, let’s traverse deeper into the file system using recursion and some more methods to use on the File object:
Files.walk()
In Java 8 and later we can use the java.nio.file.Files class to populate a Stream and use that to go through files and directories, and at the same time recursively walk all subdirectories.
Note that in this example we will be using Lambda Expressions:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Here, we’ve populated a Stream using the .walk() method, passing a Paths argument. The Paths class consists of static methods that return a Path based on a String URI — and using a Path , we can locate the file easily.
The Path , Paths , Files , and many other classes belong to the java.nio package, which was introduced in Java 7 as a more modern way to represent files in a non-blocking way.
Then, using the Collections Framework, a list is generated.
Running this piece of code will yield:
Conclusion
Handling files in some way is a core task for most programming languages, and this includes the ability to list and find files in the file system. In order to manipulate files, we need to know where they’re located. Having an overview of files in a directory is paramount if we want to accomplish this, especially if we can perform operations on them through iteration.
In this article we showed a number of different ways in Java to list files on the file system, using both linear and recursive approaches.
Источник
List files with Cloud Storage on Android
Cloud Storage for Firebase allows you to list the contents of your Cloud Storage bucket. The SDKs return both the items and the prefixes of objects under the current Cloud Storage reference.
Projects that use the List API require Cloud Storage for Firebase Rules version 2. If you have an existing Firebase project, follow the steps in the Security Rules Guide.
list() uses the Google Cloud Storage List API. In Cloud Storage for Firebase, we use / as a delimiter, which allows us to emulate file system semantics. To allow for efficient traversal of large, hierarchical Cloud Storage buckets, the List API returns prefixes and items separately. For example, if you upload one file /images/uid/file1 ,
- root.child(‘images’).listAll() will return /images/uid as a prefix.
- root.child(‘images/uid’).listAll() will return the file as an item.
The Cloud Storage for Firebase SDK does not return object paths that contain two consecutive / s or end with a / . For example, consider a bucket that has the following objects:
- correctPrefix/happyItem
- wrongPrefix//sadItem
- lonelyItem/
The list operations on items in this bucket will give the following results:
- The list operation at the root returns the references to correctPrefix , wrongPrefix and lonelyItem as prefixes .
- The list operation at the correctPrefix/ returns the references to correctPrefix/happyItem as items .
- The list operation at the wrongPrefix/ doesn’t return any references because wrongPrefix//sadItem contains two consecutive / s.
- The list operation at the lonelyItem/ doesn’t return any references because the object lonelyItem/ ends with / .
List all files
You can use listAll to fetch all results for a directory. This is best used for small directories as all results are buffered in memory. The operation also may not return a consistent snapshot if objects are added or removed during the process.
For a large list, use the paginated list() method as listAll() buffers all results in memory.
The following example demonstrates listAll .
Kotlin+KTX
Paginate list results
The list() API places a limit on the number of results it returns. list() provides a consistent pageview and exposes a pageToken that allows control over when to fetch additional results.
The pageToken encodes the path and version of the last item returned in the previous result. In a subsequent request using the pageToken, items that come after the pageToken are shown.
The following example demonstrates paginating a result:
Kotlin+KTX
Handle errors
list() and listAll() fail if you haven’t upgraded the Security Rules to version 2. Upgrade your Security Rules if you see this error:
Other possible errors may indicate the user does not have the right permission. More information on errors can be found in the Handle Errors.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник