So in my react-native module I Want to find the already created files that my app has created in
/storage/emulated/0/Download/xx/xx
It work great when My app create those files in those directory and File.listFiles("/storage/emulated/0/Download/xx/xx") return all those files without any problem.
Now when I uninstall my app and install it again, listFiles cant find those old files anymore!!
But only find the files that I create a new.
Now for those of you who think this is about permission I already check it and have full access
status{"android.permission.WRITE_EXTERNAL_STORAGE":"granted","android.permission.READ_EXTERNAL_STORAGE":"granted"}
Here is the Java method that I have
#ReactMethod(isBlockingSynchronousMethod = true)
public String getAllAppDownloadedFiles(String folderPath) {
File folder = new File(folderPath);
String result = "";
if (!folder.exists())
return result;
File[] files = folder.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isFile())
result += file.getAbsolutePath() + (files.length - 1 > i ? "," : "");
}
return result;
}
I should point out that the problem only exist when I run the app on my mobile and not in emulator. I suspect it has to do with the version of API.
Any Idea how I could fix this?
I have a folder in root with some files I want to list but the array returns null:
String path = getenv("EXTERNAL_STORAGE") + "/Files";
File directory = new File(path);
File[] files = directory.listFiles();
Permissions are granted
First off, you need to use Environment.getExternalStorageDirectory() instead of getenv():
String path = Environment.getExternalStorageDirectory().toString() + "/Files";
File directory = new File(path);
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++)
Log.d("Files", "FileName:" + files[i].getName());
But a very important note is the /storage/emulated/0 folder does not really exist. It's what might be called a "symbolic link", or, in simpler terms, a reference to where the real data is stored. That's why your array returns null. You'll need to find the actual physical location on your device where it is stored.
Version Android SDK 5.1
I do this Code.
String path = Environment.getExternalStorageDirectory().getPath();
String innerPath = "/xxxx/strage/Download/"
StringPath = path + innerPath;
File[] files = new File(targetPath).listFiles();
for(File f:files){
f.delete();
}
after execute this code, I checked Dir by "FileCommander.apk" I confirm deleted.
but when conect this Android to PC And Check this Directory, not deleted.
Please help me.
File file= new File(android.os.Environment.getExternalStorageDirectory(),"MyFolder"); // My Folder is Folder
if (file.isDirectory())
{
listFile = file.listFiles();
for (int i = 0; i < listFile.length; i++)
{
if(String.valueOf(listFile[i].getAbsoluteFile()).equals("/storage/emulated/0/MyFolder/Adu.jpg")){//absolute path
File f=new File(String.valueOf(listFile[i].getAbsoluteFile()));
f.delete();
}
Log.d(myTag, "Response : "+listFile[i].getAbsolutePath());
}
}
This is unfortunately a known old Android bug, which google does not care about.
In short:
Sometimes depending on the way the file was created, it is not showing in the media device storage, when Android device is connected to the PC as MTP device. They should appear (or disappear in your case) after reboot, but there are known situations when reboot didn't help too.
String innerPath = "/xxxx/strage/Download/"
seems like strage is written wrong.
shouldnt it mean String innerPath = "/xxxx/storage/Download/" ?
Here's my code so far:
String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
AssetManager mgr = getAssets();
try {
String list[] = mgr.list(path);
Log.e("FILES", String.valueOf(list.length));
if (list != null)
for (int i=0; i<list.length; ++i)
{
Log.e("FILE:", path +"/"+ list[i]);
}
} catch (IOException e) {
Log.v("List error:", "can't list" + path);
}
Yet while I do have files in that dir, it returns me list.length = 0... any ideas?
In order to access the files, the permissions must be given in the manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Try this:
String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
I just discovered that:
new File("/sdcard/").listFiles()
returns null if you do not have:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
set in your AndroidManifest.xml file.
Well, the AssetManager lists files within the assets folder that is inside of your APK file. So what you're trying to list in your example above is [apk]/assets/sdcard/Pictures.
If you put some pictures within the assets folder inside of your application, and they were in the Pictures directory, you would do mgr.list("/Pictures/").
On the other hand, if you have files on the sdcard that are outside of your APK file, in the Pictures folder, then you would use File as so:
File file = new File(Environment.getExternalStorageDirectory(), "Pictures");
File[] pictures = file.listFiles();
...
for (...)
{
log.e("FILE:", pictures[i].getAbsolutePath());
}
And relevant links from the docs:
File
Asset Manager
In addition to all the answers above:
If you are on Android 6.0+ (API Level 23+) you have to explicitly ask for permission to access external storage. Simply having
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
in your manifest won't be enough. You also have actively request the permission in your activity:
//check for permission
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
//ask for permission
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_PERMISSION_CODE);
}
I recommend reading this:
http://developer.android.com/training/permissions/requesting.html#perm-request
Updated working method
My minSdkversion is 21, so I'm using ContextCompat.checkSelfPermission() method to grant permissions apart from also adding the <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> in manifest. Thus, to get rid of the NullPointerException in spite of having files in your targeted directory, grant permissions as follows:-
MainActivity.java
public class MainActivity extends AppCompatActivity {
/*Other variables & constants here*/
private final int READ_EXTERNAL_STORAGE=100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ignore the button code
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openWebView();
}
});
/*---------------------------- GRANT PERMISSIONS START-------------------------*/
// Main part to grant permission. Handle other cases of permission denied
// yourself.
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},READ_EXTERNAL_STORAGE);
/*---------------------------- GRANT PERMISSIONS OVER-------------------------*/
}
And the function that list all the files (in MainActivity.java), thanks to #Yury:-
public void getDownloadedFile() {
String path = Environment.getExternalStorageDirectory().toString()+"/Download/";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
if(directory.canRead() && files!=null) {
Log.d("Files", "Size: " + files.length);
for(File file: files)
Log.d("FILE",file.getName());
}
else
Log.d("Null?", "it is null");
}
Your path is not within the assets folder. Either you enumerate files within the assets folder by means of AssetManager.list() or you enumerate files on your SD card by means of File.list()
Yury's answer needs some elaboration for newer versions of Android.
First, make sure to defined READ_EXTERNAL_STORAGE permission in manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Include the below, for SDK greater than or equals to Android 10(Q).
<application android:requestLegacyExternalStorage="true"...</application>
Now you can list files in a directory.
String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
String[] listOfFiles = getActivity().getFilesDir().list();
or
String[] listOfFiles = Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS).list();
Try this:
public class GetAllFilesInDirectory {
public static void main(String[] args) throws IOException {
File dir = new File("dir");
System.out.println("Getting all files in " + dir.getCanonicalPath() + " including those in subdirectories");
List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
for (File file : files) {
System.out.println("file: " + file.getCanonicalPath());
}
}
}
There are two things that could be happening:
You are not adding READ_EXTERNAL_STORAGE permission to your AndroidManifest.xml
You are targeting Android 23 and you're not asking for that permission to the user. Go down to Android 22 or ask the user for that permission.
Try these
String appDirectoryName = getResources().getString(R.string.app_name);
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getResources().getString(R.string.app_name));
directory.mkdirs();
File[] fList = directory.listFiles();
int a = 1;
for (int x = 0; x < fList.length; x++) {
//txt.setText("You Have Capture " + String.valueOf(a) + " Photos");
a++;
}
//get all the files from a directory
for (File file : fList) {
if (file.isFile()) {
list.add(new ModelClass(file.getName(), file.getAbsolutePath()));
}
}
If you are on Android 10/Q and you did all of the correct things to request access permissions to read external storage and it still doesn't work, it's worth reading this answer:
Android Q (10) ask permission to get access all storage. Scoped storage
I had working code, but me device took it upon itself to update when it was on a network connection (it was usually without a connection.) Once in Android 10, the file access no longer worked. The only easy way to fix it without rewriting the code was to add that extra attribute to the manifest as described. The file access now works as in Android 9 again. YMMV, it probably won't continue to work in future versions.
For the people are still getting NullPointerException when they try to get file list, if you using Android API 29+ then you need to add
<application android:requestLegacyExternalStorage="true"...
in your AndroidManifest.xml file.
Then request for storage permission again.
Simple way to list files in android device in a specific folder
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
IN Kotlin
val fileRoot = Environment.getExternalStorageDirectory()
val yourDir = File(fileRoot, "FOLDER_NAME")
for (f in yourDir.listFiles()!!) {
if (f.isFile){
print(f.name)
}
}
All the file name will be printed with the file extension
My program checks if a specific file exists in the default cache folder. If the file exists, it opens it and reads the contents. If the file does not exist, the file gets pulled from the web and is stored in the cache folder. The problem I'm having is that, no matter if the file is in the cache folder or not, my file test always returns false. The funny thing is that, even though the file test returns false, I can still open the file from the cache folder and read it. I can pull a list of files in the cache folder and I can see the file is there, but when I do the file test to see if the file is there, it returns false, even though I know the file is there and I can open it and see it's contents.
I tried the regular exists() test and even reading each file in the cache directory one by one and comparing the name to the file I'm looking for and still returns false.
Thanks for any help in advance!
String file = "test.txt"
String content = "testing";
putFile(file, content);
Boolean fileIsThere = checkFile(file);
public Boolean checkFile(String file){
Boolean fileExists = false;
// regular file test - always returns false, even if the file is there
File f = new File(file);
if (f.exists())
fileExists = true;
// comparing each individual file in the directory - also returns false
String[] dirFiles = fileList();
for (int i = 0; i < dirFiles.length; i++) {
if (dirFiles[i] == file){
fileExists = true;
break;
}
}
return fileExists;
}
public void putFile(String file, String content){
try {
FileOutputStream fos = openFileOutput(file, Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
Log.w("putFile", "Error (" + e.toString() + ") with: " + file);
}
}
Any ideas? I'm thinking that since I'm putting the files in the cache folder, I will always get false on the file test. I just want to see if anyone else came across this and has a fix for it, or if I have to make a specific directory and store my files there, or something else. Could "Context.MODE_PRIVATE" in putFile() have anything to do with it?
If you want to test existention of file stored in your Context storage data/data/nameOfPackage/files/text.txt you have to rewrite String file like this
String file = "/data/data/nameOfPackage/files/test.txt"
Then you can check exists() method of your test.txt file. I hope it will help you. :)
if (f.exists() && f.length() > 0) fileExists = true;
This works for me!