I wish delete music file stored on my phone (has no SD card) in Music folder. I have file path and File.exists() said true. Next, File.delete() also said true, but file stay in its place. But! After "deletion" I can no longer play this file, edit name and also can't copy it. But I can delete it manually.
I've set android.permission.WRITE_EXTERNAL_STORAGE. OS 4.4.4 GPE
Where is my mistake? Any suggestions, thanks.
File file = new File(Path);
if (file.exists()){
file.setWritable(true, false);
return file.delete();
}
Windows is not looking at external storage directly. It is looking at the data served up by the Media Transfer Protocol (MTP) server on your Android device. It, in turn, is working with the MediaStore index, not the actual filesystem.
If you make any change to external storage, such as deleting a file, you need to update MediaStore. Off the cuff, I do not recall exactly how to do that for a deleted file, though I would consider trying to use MediaScannerConnection and scanFile() to perhaps scan the directory that contained the deleted file.
So, my final solution that seems to work is:
public Boolean deleteTrack(String key){
MusicTrack track = getAlbum(0).getTrackByKey(key);
if (track == null) return false;
File file = new File(track.getData().Path);
if (file.exists()){
file.setWritable(true, false);
String where = MediaStore.Audio.Media.DATA +"=\""+ track.getData().Path +"\"";
if (context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, where, null) == 1){
if (file.exists()){
Boolean d = file.delete();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
return d;
}
return true;
}
}
return false;
}
Related
I put some .mp4 file in a folder in my android device internal storage. And then I play this file from my application. It plays well if exists otherwise app crushed.
So before play file I want to check its existence.
I tried below code but no luck.
File file = new File("file:///storage/emulated/0/tutorial/1a1cbfc4-18cb-4637-8405-01bf9bebeda3.mp4");
if (file.exists()) {
LogUtil.printLogMessage(VideoListActivity.class.getName(), "video File", "file exist");
} else {
LogUtil.printLogMessage(VideoListActivity.class.getName(), "video File", "file not exist");
}
i am sure the file is exist in the folder named tutorial in my internal storage.
Use file.isFile() for file & file.isDirectory() for directory,
file.exists() tries to access the file which causes it to crash if the file doesn't exist, file.isFile() uses linux stat, which only returns the information about the file without trying to access it.
Please make proper file name, Replace with File myDirectory = new File(Environment.getExternalStorageDirectory(), dirName);
public Boolean checkFile(){
File file = new File("/storage/emulated/0/tutorial/1a1cbfc4-18cb-4637-8405-01bf9bebeda3.mp4");
if (file.exists()) {
return true;
} else {
return false;
}
}
Use checkfile True/False flag before video play.
Try this
File file = new File(path);
if (!file.isFile()) {
}else{
}
I want to know whether it is possible to write data in /etc folder (or any other folder besides data)? If yes, how to do that?
And if not possible, any way to store a permanent data? For scenario example, an app is uninstalled (or clear data), but a specific file will still remain.
thank you.
i'm not sure about /etc folder, but the stuff saved in /data folder is managed by android automatically itself. So when you uninstall an app, anything related to it is also removed from data folder.
However, to store a file permanently besides Data folder on your SdCard, see the code below:
public static boolean saveOnFile(String msg){
boolean saved = false;
String filename = "yourFileName.extension";
try{
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File root = new File(Environment.getExternalStorageDirectory(), "/YourFolderOnSdCard/");
//create root folders if they do not exist
if(!root.exists()){
root.mkdirs();
}
//now lets save file in our directory structure
File file = new File(root, filename);
FileWriter fw = new FileWriter(file);
fw.append(msg);
fw.flush();
fw.close();
saved = true;
}
else
Log.e("Save", "Mounted media is not available or is write-protected");
}
catch (Exception e) { Log.e("Save", e.toString()); }
return saved;
}
This Data Storage guide could be useful.
I develop an app which collects some data from internet. Then save it to a temporary folder. To build this app I need to create and access a folder ( just for the purpose of app, not for the user). How can I do it?
this code is to create folder:
File direct = new File(Environment.getExternalStorageDirectory() + "/New Folder");
if(!direct.exists())
{
(direct.mkdir()) //directory is created;
}
try it may help you
File mFile;
onCreate()
mFile= new File(Environment.getExternalStorageDirectory()+"/temp/";
mFile.mkdir();
onDestroy();
mFile.delete();
try out this...
private void makeFolder(){
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + getString(R.string.folder_name));
boolean mainfolderexist = root.exists();
if (!mainfolderexist) {
try {
if (Environment.getExternalStorageDirectory().canWrite()) {
root.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
All The best
You should really check this other SO answer: https://stackoverflow.com/a/6485850/65716
Aside from the fact that you have to completely manage your use of the space, etc, caching on external storage requires more permission for your app.
See http://developer.android.com/reference/android/content/Context.html#getCacheDir()
"Apps require no extra permissions to read or write to the returned path, since this path lives in their private storage."
For app use only, I would recommend to use Context.getDir() for retrieving the directory if the files is used by our app only and don`t want to be visible to users by file browsers.
// No need to check if exist, created automatically.
File tempRoot = context.getDir("temp", Context.MODE_PRIVATE);
// do something
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!
I have used the Android internal storage to save a file for my application (using openFileOutput) but I would like to delete that file, is it possible and how?
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
I know this is a bit of an oldie, but the docs say to use:
deleteFile("filename");
rather than:
File.delete();
Which if you are already using:
getFilesDir();
kind of makes sense.
You should always delete files that you no longer need. The most straightforward way to delete a file is to have the opened file reference call delete() on itself.
myFile.delete();
If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling deleteFile():
myContext.deleteFile(fileName);
Note: When the user uninstalls your app, the Android system deletes the following:
All files you saved on internal storage
All files you saved on external storage using getExternalFilesDir().
However, you should manually delete all cached files created with getCacheDir() on a regular basis and also regularly delete other files you no longer need.
Source : http://developer.android.com/training/basics/data-storage/files.html
If you want to delete all files from a folder then use the following function:
private void deleteTempFolder(String dir) {
File myDir = new File(Environment.getExternalStorageDirectory() + "/"+dir);
if (myDir.isDirectory()) {
String[] children = myDir.list();
for (int i = 0; i < children.length; i++) {
new File(myDir, children[i]).delete();
}
}
}
Folder must be present on storage. If not we can check one more codition for it.
if (myDir.exists() && myDir.isDirectory()) {
//write same defination for it.
}
new File(mUri.toString).delete();
void clearMyFiles() {
File[] files = context.getFilesDir().listFiles();
if(files != null)
for(File file : files) {
file.delete();
}
}
Another alternative in Kotlin
val file: File = context.getFileStreamPath("file_name")
val deleted: Boolean = file.delete()
Use delete method of File