Delete file in internal memory from Android device? - java

I am trying to delete a file stored in internal memory. The file does gets deleted by using
activity.deleteFile(filename);
but only in emulator. On the actual device the method always returns false. When I try to access the file from adb shell there is permission denied being displayed. So, I guess there is permission related issue with deleting the files in internal memory.
Can someone let me know how to actually delete the file from internal memory in Android?

If you're talking about just any file in the file system... Does this not work?
if (new File("fileUrl").delete()) {
// Deleted
} else {
// Not deleted
}

Due to security constraints you can only delete files that were created by your app. You also can not delete files that are part of your app package (apk), i.e. files in /res, /assets, etc..

Here FileName is the name of File which you want to delete and without path separator.that mean FileName should not contain path separator like "/".
And File should be created by your application.
My Problem was solved by that code..
if(getApplicationContext().deleteFile(FileName))
{
Toast.makeText(getApplicationContext(),"File Deleted",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Not Deleted",Toast.LENGTH_SHORT).show();
}

You should use:
_context.openFileOutput(fileName, Context.MODE_WORLD_READABLE);
when writing the file

Related

How to remove A file from removable/secondary SD card

I want to delete a file from the removable sd card, I tried many ways but nothing did the job.
Tried:
file.delete();
and
File file = new File(selectedFilePath);
boolean deleted = file.delete();
and
DocumentFile documentFile = DocumentFile.fromFile(file);
documentFile.delete();
and
DocumentsContract.deleteDocument(context.getContentResolver(),
Uri.fromFile(file );
none of which deletes the file
I want to delete a file from the removable sd card
In general, you can't.
If you put the file in one of the Context locations (getExternalFilesDirs(), etc.), then you should be able to delete it, using delete() on a File object.
If this is some other file, you do not have permission to do anything with it, including delete it.
And on Android Q, you will not have much access to external or removable storage at all.
You are welcome to use the Storage Access Framework (e.g., ACTION_OPEN_DOCUMENT, ACTION_OPEN_DOCUMENT_TREE) and work with content that way.
i am trying to work on file explore
Android Q is severely restricting that entire app category. I recommend that you build something else.

android deleting a file from internal storage

I have created a file stored on internal storage from an activity. How can I delete this file from another activity?
I'm thinking I'll have to get the file's directory (which I'm not sure how to) and delete it. I tried using
context.deleteFile();
but it won't work because I'm trying to call it from a non-static method.
Here is your answer :
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
You can try getting the instance pointing to the file and deleting it like in
this answer
or this one

File.renameTo() fails

I have eclipse plugin jface application.
A thread writes file via BufferedWriter.
After writing is done I close the buffer after that I try to rename the file.
But sometimes file is not renamed!
I tried to add some Thread.Sleep(BIG_NUMBER) between couple of retries this didn't help.
It looks like the file getting some kind of lock. (when I kill the jvm I can rename the file).
Is there something I can do?
OS: Windows XP, windows 7
JAVA version: 1.5
File.RenameTo() is platform dependent and relies on a few conditions to be met in order to succesfully rename a file, a better alternative is using
Path source = currentFile.toPath();
try {
Files.move(source, source.resolveSibling(formattedName));
} catch (IOException e) {
e.printStackTrace();
}
Read more here.
From the javadocs:
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
Note that the Files class defines the move method to move or rename a file in a platform independent manner.
For the File.renameTo() to work,The file will need to be somehow writable by external applications.
You can also do something like below:
File o=new File("oldFile.txt");
File n=new File("newFile.txt");
n.delete();
o.renameTo(n);
n.delete() : We need to delete the file(new.txt) if exists.
o.rename(n) : so that the file(old.txt) is renamed as new.txt
How to find out why renameTo() failed?
Reliable File.renameTo() alternative on Windows?
http://www.bigsoft.co.uk/blog/index.php/2010/02/02/file-renameto-always-fails-on-windows
We have had issues under Windows 7 with UAC and unexpected file permissions. File#canWrite will return true even though any attempts to perform file I/O will fail.
Make sure the file you are trying to rename actually exists
Make sure that the location you are attempting to write the file (or rename the file) to is accessible. We write a simple text file to the location, check to see if it exists and that it's contents is correct (we're paranoid) before we attempt any further I/O.
This is working fine for me. Rename is done using two steps but don't forget to set permissions in manifest.xml with:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
public boolean RenameFile(String from, String to) {
to.replace(" ", ""); // clear all spaces within file name
File oldfile = new File(from);
File newfile = new File(to);
File tempfile = new File(to + ".tmp"); // add extension .tmp
oldfile.renameTo(tempfile);
return (tempfile.renameTo(newfile));
}

Directory & File Creation on Android File System

I'm trying to create a directory hierarchy and then copy a file from my assets into the newly created directory. I've used the code samples offered here on stackoverflow but I'm not getting anywhere. Essentially my code goes like this:
InputStream in = getAssets.open(mydb.sqlite);
File dir = new File("/data/data/my.package/databases/");
dir.mkdirs();
out = new FileOutputStream("/data/data/my.package/databases/mydb.sqlite");
while ((len = in.read(buffer)) > 0)
{
out.write(buffer, 0, len);
}
out.flush();
out.close();
in.close
This is all done within the main activity on first launch and of course should only be done once. Before the code runs, the only directory that exists is /data/. Yes, it is a database file but that shouldn't matter at this point since I'm just copying the file and haven't yet tried to access it with the database code.
The code doesn't throw any exceptions, and dir.mkdirs() returns true. Regardless, the directories are not created and the file is not copied. I have added the permissions line for WRITE_EXTERNAL_STORAGE to my manifest as has been suggested in several places, FWIW. I can step through the code and everything appears to be fine. But of course it's not.
What do I need to be looking for here? File permissions problems? Why does the code think everything is there (ie, when it gets to the copy code, it doesn't throw FileNotFoundException) but in reality there's nothing on the file system?
Edit: Here's what I've learned. getDir() creates the directory in /data/data/my.package/app_*. Not sure why it uses this prefix on the directory name. This won't work if you need to put something in a standard location such as databases/ or files/.
Use openFileOutput instead as /data/data is internal storage and you should only use the Android APIs to get a file handle there. See: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
Edit:
/data/data/my.package is handled by openFileOutput/getDir so you would create your directory with getDir('databases',MODE_PRIVATE) and create your file there.
Edit2:
From getDir documentation:
You can use the returned File object to create and access files in this directory.

Can't write to external storage on Android

I see a bunch of other people asking this same question, but none of the solutions posted helped me.
I'm trying to write a (binary) file to external storage from my Android app.
I put <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> into my manifest, but I still can't manage to create any files. The code I'm using to create files is
File folder = new File(Environment.getExternalStorageDirectory(), SAVE_DIRECTORY);
File toWrite = new File(folder, "save.bin");
if(!toWrite.exists()){
try {
if(!folder.mkdirs())
Log.e("Save", "Failed to create directories for save file!");
toWrite.createNewFile();
} catch (IOException e) {
Log.e("Save", "Failed to create save file! " + e.getMessage());
}
}
The call to mkdirs() fails, and the createNewFile() throws the IOException (ENOENT, because the directory doesn't exist)
Anybody know what's up? I've even tried rebooting my device. I'm on API level 8 on a Nexus 7, if it makes any difference.
first you should check the ExternalStorageState
public static boolean isSDCARDAvailable(){
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
if this method isSDCARDAvailable return true, then use your code
add the permissions:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
The documentation says that starting in API level 19, WRITE_EXTERNAL_STORAGE is not required to read/write files in your application-specific directories returned by getExternalFilesDir(String) and getExternalCacheDir(). However if you don't want to write files there and instead want to write files to getExternalStorageDirectory(), under API 23 or higher you have to request permission at run time using requestPermissions(). Once I did that I was able to create a directory in getExternalStorageDirectory().
I was suffering this issue as well and everything was properly configured in my app, i.e., I had the read and write permissions for external storage.
My problem was in the way I was creating the path to store my files:
private val LOG_BASE_PATH = Environment.getExternalStorageDirectory().path + "myFolder"
Note that it is necessary to include the "/" as follows:
private val LOG_BASE_PATH = Environment.getExternalStorageDirectory().path + "/myFolder/"
Without this, you won't be able to create the folder. Android won't fail, so you might think that there are issues with your phone configuration or app permissions.
Ideally, this helps somebody to save some precious time.

Categories

Resources