String folder = Environment.getExternalStorageDirectory()+ "/books";
File file=new File(folder);
File[] f;
f=file.listFiles(); //////f==null;
Toast.makeText(getApplicationContext(), f[1].toString(),
Toast.LENGTH_SHORT).show();
I am not able to fix the error . I need to help. Thanks.
what you can do is you can have a check like below
String path = Environment.getExternalStorageDirectory().toString()+"/books";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
if(file!=null&&file.length>0){
Toast.makeText(getApplicationContext(), f[1].toString(), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "folder is empty", Toast.LENGTH_SHORT).show();
}
what above code is doing basically it is checking that if length is greater the 0 and file objext is not null. that display the toast containing second file name in the list.
'file' is of File not Folder . That is why you can not get anything on calling file.listFiles() .
String path = Environment.getExternalStorageDirectory().toString()+"/books";
Log.d("Files", "Path: " + path);
File f = new File(path);
if (f.isDirectory()){
File file[] = f.listFiles();
Toast.makeText(getApplicationContext(), file[1].toString(), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "folder is empty", Toast.LENGTH_SHORT).show();
}
I think your directory path does not exists.
Check the documentation of File.listFiles(). It says
An array of abstract pathnames denoting the files and directories in
the directory denoted by this abstract pathname. The array will be
empty if the directory is empty. Returns null if this abstract
pathname does not denote a directory, or if an I/O error occurs.
You are giving a incorrect directory path, that is why file.listFiles(); is returning null.
As you are using Environment.getExternalStorageDirectory(), may be you have not enabled external storage for emulator. Just make sure that you have enabled external storage, this link will be helpful.
It's safer to check if f is null before accessing it:
if(f!=null){
Toast.makeText(getApplicationContext(), f[1].toString(),
Toast.LENGTH_SHORT).show(); // also size of f[], if you really want to access f[1]
}
Related
I'm trying to save pictures on my Android phone and then restore them when it's needed.
So I use RxJava to save and read this files to Environment.DITECTORY_PICTURES folder. My problem is that I can write an image (my rx method calls onNext, but not onError, debug shows the correct path, settings testify that app data size grows), but can't read from there.
When I use my reading code with the correct path its throws FileNotFoundException. When I use this test code
try {
String path = Environment.DIRECTORY_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());
}
} catch (Exception e) {
e.printStackTrace();
}
it throws NPE saying that files array is null.
I have Read/Write external storage permissions granted. Tested on Android 5 and 6, so I guess there is nothing about Runtime permissions as well.
Is there something special about reading from Environment folders I don't know?
Thanks in advance for your help!
Environment.DIRECTORY_PICTURES is not a fulll qualified path to the file system directory, the one you looking for is get trough the class and using this as argument.
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Theres more kind of storages described at:
https://developer.android.com/reference/android/os/Environment.html
I can see sdcard folder contents by using this
File f = new File("/storage/extSdCard");
if (f.exists()) {
File[] files = f.listFiles();
if (files != null) {
for (File filz : files) {
Toast.makeText(this, filz.getName() + "", Toast.LENGTH_SHORT).show();
}
}
}
But when i try to create directories
File dir = new File("/storage/extSdCard/Android/Mayor");
try {
if (!dir.exists()) {
if (dir.mkdirs()) {
Toast.makeText(this, "Folder Created", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Folder Not Created", Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "WTF", Toast.LENGTH_LONG).show();
}
Its doesnt create at all. Any idea?
// create a File object for the parent directory
File myDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
myDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(myDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
Note:
It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card (such as built-in flash, a'la the iPhone). Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.
UPDATE:
Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You need to use DocumentFile.createDirectory(displayName) to create a directory on a removable SD card. See https://stackoverflow.com/a/35175460/1048340
File mnt = new File("/storage");
if (!mnt.exists())
mnt = new File("/mnt");
File[] roots = mnt.listFiles();
For read external sdcard, you need to mount sdcard path first then after you can able to use external sdcard path.
I try a lot to create a folder in SD card in android 4.4.2 version.
i try the following code
String dirName="Test";
File file = new File(Environment.getExternalStorageDirectory(), dirName);
boolean status = file.mkdir();
if (status)
Toast.makeText(MainActivity.this,
"Directory created successfully", Toast.LENGTH_SHORT)
.show();
else
Toast.makeText(MainActivity.this, "Directory create failed",
Toast.LENGTH_SHORT).show();
but it creates a folder in internal storage.
and I try another code is
String path=System.getenv("SECONDARY_STORAGE");
File file=new File(path +"/Test123");
file.mkdir();
it creates a folder in External SDCARD in android 4.1 but not in android 4.4.2
So how can i create a folder in External sdcard in android 4.4.2??
If anyone know please help me..
Thanks in advance
The documentation states that
Applications should not directly use this top-level directory, in
order to avoid polluting the user's root namespace. Any files that are
private to the application should be placed in a directory returned by
Context.getExternalFilesDir, which the system will take care of
deleting if the application is uninstalled.
where with top-level directory they mean the return value of Enviroment.getExternalStorageDirectory()
Using getExternalFilesDir you will have
File file = new File (getExternalFilesDir(null), dirName);
if (!file.exists()) {
boolean status = file.mkdir();
if (status) {
Toast.makeText(MainActivity.this, "Directory created successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Directory create failed", Toast.LENGTH_SHORT).show();
}
}
also you should be aware of the fact that mkdir() returns false if the directory already exists
This should be self-explanatory.
String folderName = "NewFolder";
File file = new File(Environment.getExternalStorageDirectory(),
folderName);
if (!file.exists()) {
file.mkdirs();
}
Make sure you have added WRITE_EXTERNAL_STORAGE permission in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Credits to Dhaval
String extra=imagepath.get(i).toString();
String extra2=imageid.get(i).toString();
String path = "/mnt/sdcard/Android/data/com.example.webdata/files/Download/" + extra2 + ".jpg";
File f = new File(path);
if(f.exists())
{
//Toast.makeText(getApplicationContext(), "File already exists....",
// Toast.LENGTH_SHORT).show();
}
else
{
downloadfile();
}
I am using the above code to check if a file exists or not. I have checked it with one file and it works fine, but when I use it in my application where there are multiple (100-200) images it always starts downloading files whether they exist or not. Is there a better method than this?
First check how many images on folder:-
File extStore = Environment.getExternalStorageDirectory();
File[] imageDirs = extStore.listFiles(filterForImageFolders);
after above you run the loop and check u r condition:-
for(int i=0;i<list.length;i++)
{
// ur condition
}
I have a section of code that is supposed to check if an mp3 file is stored in the SD card on the MediaStore.Audio.Media content provider
the problem is that no matter the situation. Either if the file with the pathname stored in variable "audioFilename" exists on the SD card or not. it always returns "this file does not exist" as the result. Despite the fact that the variable audioFilename has the String path name stored in it "/mnt/sdCard/Music/Jungle.mp3", and this MP3 file is actually on the SD card. Easy to prove with a Toast message and a check of the SD card contents.
I probably have an error in the use of File or Environment classes. Can anyone see a problem in the code shown here?
// toast message to prove that the audioFilename is not null,
// message displayed is the string, "File name: /mnt/sdCard/Music/Jungle.mp3"
Toast.makeText(Editor.this, "File name: " + audioFilename,
Toast.LENGTH_LONG).show();
// the code below always returns "this file does not exist"
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "audioFilename");
if(myFile.exists()){
Toast.makeText(Editor.this, "<<<< this file exists, it is: "+audioFilename+" >>>>",
Toast.LENGTH_LONG).show();
} else if(!myFile.exists()){
Toast.makeText(Editor.this, "<<<< this file does not exist >>>> ",
Toast.LENGTH_LONG).show();
}
Toast.makeText(Editor.this, "audio file name is: "+ audioFilename,
Toast.LENGTH_LONG).show();
Are you sure have import java.io.File?
Try with :
String pathsd = Environment.getExternalStorageDirectory()+"/";
// so var pathsd will return "/mnt/sdcard/"
// then you must sure var audioFilename is Music/Jungle.mp3
File myFile = new File(pathsd + audioFilename);
Or are you sure with your path? if you not sure you can try give direct string path.
File myFile = new File("/mnt/sdCard/Music/Jungle.mp3");
Try to change this line
File myFile = new File(extStore.getAbsolutePath() + "audioFilename");
with
File myFile = new File(audioFilename);
I have run test with the same code and it is working well.
Here is the code I test with :
String audioFilename = "/sdcard/NewFolder/test1.jpg";
Toast.makeText(SimpleTest.this, "File name: " + audioFilename,
Toast.LENGTH_LONG).show();
// the code below always returns "this file does not exist"
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(audioFilename);
if(myFile.exists()){
Toast.makeText(SimpleTest.this, "<<<< this file exists, it is: "+audioFilename+" >>>>",
Toast.LENGTH_LONG).show();
} else if(!myFile.exists()){
Toast.makeText(SimpleTest.this, "<<<< this file does not exist >>>> ",
Toast.LENGTH_LONG).show();
}
Toast.makeText(SimpleTest.this, "audio file name is: "+ audioFilename,
Toast.LENGTH_LONG).show();
Hope it helps you.
Thanks.
You need to add permission in AndroidManifeast file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Edit :
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore+ "/Music/Jungle.mp3"); <---- try this
I'm just going to hazard a guess and assume that you are using a physical device to test your application. If this is true, your external storage may not be mounted (since you're using USB storage with the computer) so the file really doesn't exist according to the system. Try testing your code without the USB cord plugged in.
EDIT:
Remove the quotes around "audioFilename".
File myFile = new File(extStore.getAbsolutePath() + "audioFilename");
to
File myFile = new File(extStore.getAbsolutePath() + audioFilename);