I'm trying to delete images stored in internal storage. I've come up with this so far:
File dir = getFilesDir();
File file = new File(dir, id+".jpg");
boolean deleted = file.delete();
And this is from another question, which was answered with:
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
My example always returns false. I can see the file fx 2930.jpg in DDMS in eclipse.
The getFilesDir() somehow didn't work.
Using a method, which returns the entire path and filename gave the desired result. Here is the code:
File file = new File(inputHandle.getImgPath(id));
boolean deleted = file.delete();
Have you tried Context.deleteFile() ?
Java
File file = new File(photoPath);
file.delete();
MediaScannerConnection.scanFile(context,
new String[]{file.toString()},
new String[]{file.getName()},null);
Kotlin
val file = File(photoPath)
file.delete()
MediaScannerConnection.scanFile(context, arrayOf(file.toString()),
arrayOf(file.getName()), null)
String dir = getFilesDir().getAbsolutePath();
File f0 = new File(dir, "myFile");
boolean d0 = f0.delete();
Log.w("Delete Check", "File deleted: " + dir + "/myFile " + d0);
The code File dir = getFilesDir(); doesn't work because this is a request for a File object.
You're trying to retrieve the String that declares the path to your directory, so you need to declare 'dir' as a String, and then request that the directory's absolute path in String form be returned by the constructor that has access to that information.
You can also use: file.getCanonicalFile().delete();
File file = new File(getFilePath(imageUri.getValue()));
boolean b = file.delete();
is not working in my case.
boolean b = file.delete(); // returns false
boolean b = file.getAbsolutePath.delete(); // returns false
always returns false.
The issue has been resolved by using the code below:
ContentResolver contentResolver = getContentResolver();
contentResolver.delete(uriDelete, null, null);
Have you tried getFilesDir().getAbsolutePath()?
Seems you fixed your problem by initializing the File object with a full path. I believe this would also do the trick.
> 2019-11-12 20:05:50.178 27764-27764/com.strba.myapplicationx I/File: /storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/JPEG_20191112_200550_4444350520538787768.jpg//file when it was created
2019-11-12 20:05:58.801 27764-27764/com.strba.myapplicationx I/File: content://com.strba.myapplicationx.fileprovider/my_images/JPEG_20191112_200550_4444350520538787768.jpg //same file when trying to delete it
solution1:
Uri uriDelete=Uri.parse (adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ());//getter getImageuri on my object from adapter that returns String with content uri
here I initialize Content resolver
and delete it with a passed parameter of that URI
ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );
solution2(my first solution-from head in this time I do know that ): content resolver exists...
String path = "/storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/" +
adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ().substring (58);
File file = new File (path);
if (file != null) {
file.delete ();
}
Related
I wanted to download images that are downloaded from Dropbox and cache them for further use:
String cachePath = mContext.getCacheDir().getAbsolutePath() + entry.fileName();
File cacheFile = new File(cachePath);
//cacheFile.exists() returns true after 1st call
if(!cacheFile.exists()){
//If cache doesn't exist, download the file
mFos = new FileOutputStream(cachePath);
mApi.getThumbnail(path, mFos, ThumbSize.BESTFIT_320x240,
ThumbFormat.JPEG, null);
}
mDrawable = Drawable.createFromPath(cachePath);
mImageView.setImageDrawable(mDrawable);
The mDrawable is null if the code doesn't enter the if block.
If I comment the if condition it works fine. But downloads the images every time.
Edit:
The above code is from how to test for a file in cache
Try this hope helps you
String path = context.getFilesDir().getAbsolutePath() + File.separator + entry.fileName();
File file = new File(path);
if (file.exists()) {
// File exists
} else {
// File does not exist
}
I use the following code:
final File newFile = new File("/mnt/sdcard/test/");
newFile.mkdir(); // if I use mkdirs() result is the same
And it creates an empty file! Why?
You wouldn't use mkdirs() unless you wanted each of those folders in the structure to be created. Try not adding the extra slash on the end of your string and see if that works.
For example
final File newFile = new File("/mnt/sdcard/test");
newFile.mkdir();
When I need to ensure that all dirs for a file exist, but I have only filepath - i do
new File(FileName.substring(0,FileName.lastIndexOf("/"))).mkdirs();
First of all you shouldn't use a file path with "/mnt/sdcard/test", this may cause some problems with some android phones. Use instead:
public final static String APP_PATH_SD_CARD = "/Test";
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH_SD_CARD;
It creates an empty file since you added the dash.
Now that you have your path use the following code:
try {
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
}
catch(Exception e){
Log.w("creating file error", e.toString());
}
Try to use
String rootPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/test/";
File file=new File(rootPath);
if(!file.exists()){
file.mkdirs();
}
A quick question, how do i rename a file?
File to = new File(f.getAbsolutePath(), etRenameStr.getText().toString() );
f.renameTo(to);
expl();
tried like that, but doesn't seem to work.
Thanks!
File dir = Environment.getExternalStorageDirectory();
if(dir.exist()){
File from = new File(dir,"from.mp4");
File to = new File(dir,"to.mp4");
if(from.exist())
from.renameTo(to);
}
http://developer.android.com/reference/java/io/File.html#renameTo%28java.io.File%29
I think getAbsolutePath() returns the full path including file name, that might be a problem here. Try getParent() instead and see if it works.
File rootDir = Environment.getExternalStorageDirectory();
File file = new File(rootDir + "/Files/"+fileName);
File file2 = new File("newname");
// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
System.out.println("File was not successfully renamed");
}
This worked for me. please check once!!
imagedirectory = new File(path);
imagepool = imagedirectory.listFiles();
Uri targetdelete = Uri.fromFile(imagepool[photoindex]); //photoindex is integer 1
File filetodelete = new File(targetdelete);
boolean deleted = filetodelete.delete();
I am receiving an error in this line
File filetodelete = new File(targetdelete);
it says targetdelete must be a string object.... I thought it was valid to put Uri object as the agrument when initializing a File object?
Thanks once again, wonderful experts on stack overflow!!
Why not just do deleted = imagepool[photoindex].delete();
I want to check if a text file exists on the SD card. The file name is mytextfile.txt. Below is the code:
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
How can I check whether this file exists?
This should do the trick, I've replaced the hard coded SDcard reference to the recommended API call getExternalCacheDir():
File file = new File(getExternalCacheDir(), "mytextfile.txt" );
if (file.exists()) {
//Do action
}
See this file System in android : Working with SDCard’s filesystem in Android
you just check
if(file.exists()){
//
}
*Using this you can check the file is present or not in sdcard *
File file = new File(sdcardpath+ "/" + filename);
if (file.exists())
{
}
You have to create a file, and set it to be the required file, and check if it exists.
String FILENAME="mytextfile.txt";
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME);
if (fileToCheck.exists()) {
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
}
Have Fun!
The FileOutputStream constructor will throw a FileNotFound exception if the specified file doesn't exist. See the Oracle documentation for more information.
Also, make sure you have permission to access the SD card.
check IF condition with Boolean type like
File file = new File(path+filename);
if (file.exists() == true)
{
//Do something
}