Naturally I thought to delete a file means to remove it from existence. So when I do
File file = new File(absPath);
....//add content
file.delete();
I expect that no further operation can be executed on file or it would throw an exception. But how come I can still add content to the file such as shown here Android saving Bitmap to SD card. So how do I delete a file so that it is completely gone? So that when someone go look through file manager, the file is no longer there? I am not in a position to test this now, so I was hoping for authoritative reference.
how come I can still add content to the file such as shown here Android saving Bitmap to SD card.
That code creates a new file after deleting the old one.
So how do I delete a file so that it is completely gone? So that when someone go look through file manager, the file is no longer there?
Call delete() on a File object that points to the file. Then, do not use that same File object to write to the file again, thereby creating a new file, as the code that you link to does.
Related
If I call File.delete() are the effects on the underlying file system immediately visible? Can I write to the same file name in the same process/thread after without worrying about bad things happening? If not, is there a way to sync the underlying file system with just a File object?
File.delete() return a boolean telling you if the file has been correctly deleted.
So you could write something like :
if(yourFile.delete()) {
//keep doing what you want. You are now sure file has been deleted !
}
Also, before writing a new file, you could check if a file with the same name already exists.
From Oracle documentation :
Returns:
true if and only if the file or directory is successfully deleted; false otherwise
Oracle source
Also there is a SO thread that might help you
How can I check If a file that I have selected from the list of files is database type or not in android ? The others files may be a text file, apk file or can be of any format. I assume not depending upon the extension of the file like .txt, .apk, .pdf etc as extension of the file can be changed also.
Thank You..!!
If you are using a subclass of SQLiteOpenHelper, you can create a new object with the file in question, and then call getReadableDatabase ().
If tha file is a database, no exception will be thrown.
Otherwise, a SQLiteDatabaseCorruptException will be trhown.
So you can surround your code with a try-catch block, and if an exception is thrown, then that file is not a database; otherwise, it is.
check by extension of file. Normally database file has extension as .db , .sql etc
I need to read some data from file in internal storage, then remove and rewrite file with new data. What is the best way to do it(safest method for data)?
I'd first rename the original file (append something like .orig), then read it, write the new file and when all that's successful, remove the renamed original file. This ensures the most that no data gets lost.
What's the best way to create a temporary file in Android?
Can File.createTempFile be used? The documentation is very vague about it.
In particular, it's not clear when temporary files created with File.createTempFile are deleted, if ever.
This is what I typically do:
File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", ".extension", outputDir);
As for their deletion, I am not complete sure either. Since I use this in my implementation of a cache, I manually delete the oldest files till the cache directory size comes down to my preset value.
Best practices on internal and external temporary files:
Internal Cache
If you'd like to cache some data, rather than store it persistently,
you should use getCacheDir() to open a File that represents the
internal directory where your application should save temporary cache
files.
When the device is low on internal storage space, Android may delete
these cache files to recover space. However, you should not rely on
the system to clean up these files for you. You should always maintain
the cache files yourself and stay within a reasonable limit of space
consumed, such as 1MB. When the user uninstalls your application,
these files are removed.
External Cache
To open a File that represents the external storage directory where
you should save cache files, call getExternalCacheDir(). If the user
uninstalls your application, these files will be automatically
deleted.
Similar to ContextCompat.getExternalFilesDirs(), mentioned above,
you can also access a cache directory on a secondary external storage
(if available) by calling ContextCompat.getExternalCacheDirs().
Tip: To preserve file space and maintain your app's performance, it's
important that you carefully manage your cache files and remove those
that aren't needed anymore throughout your app's lifecycle.
For temporary internal files their are 2 options
1.
File file;
file = File.createTempFile(filename, null, this.getCacheDir());
2.
File file
file = new File(this.getCacheDir(), filename);
Both options adds files in the applications cache directory and thus can be cleared to make space as required but option 1 will add a random number on the end of the filename to keep files unique. It will also add a file extension which is .tmp by default, but it can be set to anything via the use of the 2nd parameter. The use of the random number means despite specifying a filename it doesn't stay the same as the number is added along with the suffix/file extension (.tmp by default) e.g you specify your filename as internal_file and comes out as internal_file1456345.tmp. Whereas you can specify the extension you can't specify the number that is added. You can however find the filename it generates via file.getName();, but you would need to store it somewhere so you can use it whenever you wanted for example to delete or read the file. Therefore for this reason I prefer the 2nd option as the filename you specify is the filename that is created.
You can use the cache dir using context.getCacheDir().
File temp=File.createTempFile("prefix","suffix",context.getCacheDir());
You can use the File.deleteOnExit() method
https://developer.android.com/reference/java/io/File.html#deleteOnExit()
It is referenced here https://developer.android.com/reference/java/io/File.html#createTempFile(java.lang.String, java.lang.String, java.io.File)
Do it in simple. According to documentation
https://developer.android.com/training/data-storage/files
String imageName = "IMG_" + String.valueOf(System.currentTimeMillis()) +".jpg";
picFile = new File(ProfileActivity.this.getCacheDir(),imageName);
and delete it after usage
picFile.delete()
In Reference to this android file download problem
Can anyone explain what does this line mean in the code
FileOutputStream f = new FileOutputStream(new File(root,"Video.mp4"));
And what does it mean by the parameter root within the File().
Do I need to specify the root path to save the file?
If it is the case then how do we specify the root path in android ?
Regards
And what does it mean by the parameter root within the File(). Do I need to specify the root path to save the file? if it is the case then how do we specify the root path in android?
The code snippet from the question you linked doesn't define the variable, but if the code is downloading a file to the device, I would assume that it's a path on the SD card. Environment.getExternalStorageDirectory() will give you the root path to the SD card. You'll also need to specify the WRITE_EXTERNAL_STORAGE permission in your manifest.
If you're working on the emulator, you can create a virtual SD card when you create the emulator image.
The java.io.File(File, String) or java.io.File(String, String) are standard java constructors for Java. The first argument is just the parent directory path, while the second is the actual file name. If the file is in the current working directory or you know the full path as one string you can avoid the 2 argument constructors.
Since you are trying to download a file you can just acquire the file through a normal URL.openStream() to get an InputStream to get the contents of your downloaded file. For writing the data out you will follow the example you linked to to write the contents.
I'm unsure what the root variable was pointed to in the example. I'm not able to help you beyond this though since I have only gone through the first Hello, Android example myself.