I created folder inside application directory.
File dir = new File(getActivity().getFilesDir().getParent() + File.separator + "Image directory");
in that again i created folder for specify contents
File dir1 = new File(getActivity().getFilesDir().getParent() + File.separator + "Image directory" + File.separator+ "Image 1");
Inside that I am going to storage images. Images are stored and accessed.
I want to delete all images which are stored at dir1 location.
I tried
if(dir1.isDirectory())
{
for (int j = 0; j < dir1.length; j++)
{
File file = new File(dir1, dir1[j]);
//file.canExecute();
file.delete();
}
}
file.delete(); returns false each time.
I added permissions in manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
In your file.delete method you have used bundle don't know where did that came from.
Below code will delete all files in your Image Directory
File dir1 = new File(getActivity().getFilesDir().getParent() + File.separator + "Image directory" + File.separator+ "Image 1");
if (dir1 .isDirectory()) {
String[] children = dir1 .list();
for (int i = 0; i < children.length; i++) {
new File(dir1 , children[i]).delete();
}
}
Make sure you have permission for writing in external memory, which you already have
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Related
This is what I tried.
private void createFolderInExternalStorage() {
String storagePath = System.getenv("SECONDARY_STORAGE");
Log.e("storagePath->",storagePath);
String path = "not available";
if (storagePath != null) {
Log.e("Path->", "" + storagePath);
File file = new File(storagePath.toString());
Log.e("readable->", "" + file.canRead());
Log.e("writable->", "" + file.canWrite());
Log.e("executable->", "" + file.canExecute());
dir = new File(storagePath + File.separator+etFolder.getText().toString());
if (!dir.exists()) {
dir.mkdirs();
Toast.makeText(this,"Folder "+etFolder.getText().toString()+" created",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Folder "+etFolder.getText().toString()+" already exists",Toast.LENGTH_SHORT).show();
}
path = dir.getPath();
} else {
Toast.makeText(this,"External Storage not available",Toast.LENGTH_SHORT).show();
}
tv.setText("External SDCARD path->" + path);
}
if Secondary storage is present then System.getenv("SECONDARY_STORAGE") return /storage/sdcard1 in my case but getting following:
03-21 12:02:26.827 14155-14155/com.think.teststorage E/readable->: false
03-21 12:02:26.827 14155-14155/com.think.teststorage E/writable->: false
03-21 12:02:26.828 14155-14155/com.think.teststorage E/executable->: false
Even in some devices getting the above status as true but folder creation fails.
I have added the permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Suggestions are welcome.
You can use this code to create a folder.
File dir = new File("path/of/your/folder");
try{
if(dir.mkdir()) {
System.out.println("Folder created");
} else {
System.out.println("Folder is not created");
}
}catch(Exception e){
e.printStackTrace();
}
Add this permission also :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For further reference : see this link
Let me know if this works for you! :)
Use the following lines:
//Define the path you want
String path = Environment.getExternalStoragePublicDirectory(Environment.YOUR_DIRECTORY) + File.separator + "YourFolderName";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
YOUR_DIRECTORY is the directory where you want to create the folder, for example: DIRECTORY_DOCUMENTS, DIRECTORY_DOWNLOADS, DIRECTORY_PICTURES etc.
In your manifest should to add permission for write:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Hope it help!
It is very simple and straightforward in android
`
File mFolder = new File(Environment.getExternalStorageDirectory(), "Folder_Name");
if (!mFolder.exists()) {
mFolder.mkdirs();
mFolder.setExecutable(true);
mFolder.setReadable(true);
mFolder.setWritable(true);
}
`
Also include required permissions in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Just put these lines of code,
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
and add require permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Does not work on KitKat, external, physical sdcard ??
then use use
Environment.getExternalStorageDirectory().getPath();
I tried this one : How to access all mp3 files from all the subfolders in the sdcard?
I need to list all .amr files from a folder (ABC) and on click of any list item, do something.
Thanks in advance.
You can try this:
String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
//here populate your listview
Log.d("Files", "FileName:" + file[i].getName());
}
This will list all the files in the pictures folder. Use the path to your folder to get the files in that folder
Dont forget to use the following permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am trying to create a folder within sdcard folder like: /mnt/sdcard/eventImages/ but every time getting New Folder Error - Read Only file system.
I am working on Windows XP
Code:
private List <String> getSD()
{
List <String> it = new ArrayList <String>();
File f = new File ("/mnt/sdcard/mydata/");
File[] files = f.listFiles ();
for (int i = 0; i <files.length; i++)
{
File file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}
return it;
}
Make sure you have the required permission for that
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Code to check and create Directory if it does not exists
private void _dirChecker(String dir) {
File f = new File(dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
Try this one...
File direct = new File(Environment.getExternalStorageDirectory()+ "/eventImages/");
if (!direct.exists())
{
direct.mkdir();
}
and put this permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
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
ANSWER:
Needed the call to getExternalFilesDir(p); like so:
String p = thepathblah;
File path=context.getExternalFilesDir(p);
EDIT EDIT:
While I knew the Environment.DIRECTORY_PICTURES was returning just Pictures/ I figured this worked because in android I assumed the file pointer was already pointing to your application space (sorta like in c#). So in this:
String p = Environment.DIRECTORY_PICTURES + "/" + s.getClient().getFirstName()+s.getClient().getLastName() +
"/" + s.getPackage().getName() +
(mSession.getSessionDate().getMonth()+1) +
mSession.getSessionDate().getDate() +
(mSession.getSessionDate().getYear()+1900);
I thought was getting the full path, in fact I was writing a file out to this with no issues. It turns out though to delete individual files (and load them) I needed a fuller path which ended up being:
String p = Environment.DIRECTORY_PICTURES + "/" + s.getClient().getFirstName()+s.getClient().getLastName() +
"/" + s.getPackage().getName() +
(mSession.getSessionDate().getMonth()+1) +
mSession.getSessionDate().getDate() +
(mSession.getSessionDate().getYear()+1900);
File dir = new File("/sdcard/Android/data/com.software.oursoftware/files/"+p);
Not sure if I can take it that the above link is valid for all Honeycomb devices or not, specifically the /sdcard/Android/data/packagespace/files/
Is this safe to use this or do I have to do something more dynamic for honeycomb devices???
EDIT: This is my little test function code to just write something to a folder...
String p = Environment.DIRECTORY_PICTURES + "/" + s.getClient().getFirstName()+s.getClient().getLastName() + "/" + s.getPackage().getName() + (mSession.getSessionDate().getMonth()+1) + mSession.getSessionDate().getDate() + (mSession.getSessionDate().getYear()+1900);
File path = mContext.getExternalFilesDir(p);
File file = new File(path, "DemoPicture.jpg");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.ic_contact_picture);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(mContext,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String arg0, Uri arg1) {
Log.i("ExternalStorage", "Scanned " + arg0 + ":");
Log.i("ExternalStorage", "-> uri=" + arg1);
}
});
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
Then the way I try to delete this folder:
String p = Environment.DIRECTORY_PICTURES + "/" + firstName+lastName +"/" + pName+pDate;
File dir=new File(p);
deleteRecursive(dir);
results in
Pictures/ShaneThomas/Portrait882011/
Which can write a file, tested that, but if I try to say:
void deleteRecursive(File dir)
{
Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
File temp = new File(dir, children[i]);
if(temp.isDirectory())
{
Log.d("DeleteRecursive", "Recursive Call" + temp.getPath());
deleteRecursive(temp);
}
else
{
Log.d("DeleteRecursive", "Delete File" + temp.getPath());
boolean b = temp.delete();
if(b == false)
{
Log.d("DeleteRecursive", "DELETE FAIL");
}
}
}
dir.delete();
}
}
The dir.isDirectory is always false!? I got this delete file/directories code off stack overflow but am puzzled as to why its not working?
and I do have this set:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
There are several reasons for File.isDirectory() to return false:
The path points to file (obviously), and not to directory.
The path is invalid (i.e. there is no such file/directory exists).
There is not enough permissions granted to your application to determine whether path points to directory.
In general, if isDirectory() returns true, you've got path that points to directory. But if isDirectory() returns false, then it might be or might not be a directory.
In your particular case, the path most likely does not exist. You need to call dir.mkdirs() to create all directories in the path. But since you need that to only recursively delete them, then there is no point in calling dir.mkdirs() just to remove that directory after that.
I think you want to add
dir.mkdirs() right after File dir=new File(p). mkdirs() is the method responsible for actually creating a directory, not new File().
Ok it's answered, but sometimes the issue fires because of sample reasone:permission :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
if you forgot this permission you will always get false result.