How to Delete files in /data/data/providers/downloads/cache on Android - java

I want to create and delete some files located in /data/data/providers/downloads/cache. So far, I can download target files and save in /data/data/providers/downloads/cache successfully, but when I trying to delete a file located in /data/data/providers/downloads/cache it fails in the end. My methods are as follows
File directory = new File("/data/data/providers/downloads/cache");
File[] files = directory.listFiles();
I want to list all files, so that I can find the target files need to be deleted.
I found that listFiles() method always return NULL, so my question is, can I use listFile() to the dir /data/data/providers/downloads/cache ?
Any ideals are welcomed.
BR
Alan

I use this method: when i want to delete all the files including the directory.
static public boolean deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
if (files == null) {
return true;
}
for(int i = 0; i < files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
Log.d("Deleting Files", files[i].getPath());
}
}
return( path.delete() );
}
But android has it's own clear cache method you can use, but it requires you to actually save stuff to the cache. The problem might be that you never add anything to it, and you only have permission to clear your own cache?
How do I take advantage of Android's "Clear Cache" button Discusses the problem anyway :)
Good luck
EDIT:
Also, are you sure your file path is correct? You can use
Environment.getDownloadCacheDirectory()
in order to find the root directory to the cache i think?

Related

Searching for specific files on a device

I'm a newcomer to mobile programming and want to start off with a little Musicplayer-App. I need to search for all files which end with .mp3, .m4a, .wav, and so on. To do this, I want to first get a list of all files and then filter out the audio-files.
However, when I use getExternalStorageDirectory to get the path to the storage it returns "/storage/3139-6333", which is obviously not correct.
Basically I'm just curious why I get this result and how to fix it.
It's to be assumed that READ_EXTERNAL_STORAGE is permitted.
Thanks in advance.
String state = Environment.getExternalStorageState();
if ((Environment.MEDIA_MOUNTED.equals(state)||Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)))
{
File sd_card = Environment.getExternalStorageDirectory(); //"/storage/3139-6333"
File[] listFile = sd_card .listFiles(); //null
}
I guess you already have the path where you wish to do file search, if yes then you can use basic dfs algorithm to search your desired file.
below is example code for that, you can put any format in end to check all files for it.
public void search(String path){
File file = new File(path);
File[] files = file.listFiles();
if (files!=null) {
for (File f : files) {
if (f.isDirectory()) {
this.search(f.getAbsolutePath());
}
if (f.getAbsolutePath().endsWith(".txt")) {
System.out.println(f.getAbsolutePath());
}
}
}
}
hope this will help.

What is the right way to check if a file is in a directory?

I am not asking how to check if a file exists or how to check if a file is in a specific directory level. Rather I want to know how to check if an existing file is anywhere underneath a specified directory.
Obviously if a file is a direct child of a directory that is easy to check. But what I want to be able to do is efficiently check if an existing file is in a directory including any possible subdirectory. I'm using this in an Android project where I am keeping fine grain control over my cache and I want a utility method to check if a file I may be manipulating is in my cache folder.
Example:
cache dir
/ \
dir file1
/ \
file2 file3
isCacheFile(file2) should return true
Currently I have a method that does it like so
private static final File cacheDir = AssetManager.getInstance().getCacheDir(); // Not android.content.res.AssetManager
private static final String cacheDirName = cacheDir.getAbsolutePath();
public static boolean isCacheFile(File f) {
if (!f.exists()) return false;
return f.getAbsolutePath().startsWith(cacheDirName);
}
However, I am inclined to believe there is a better way to do this. Does anyone have any suggestions?
If you have a known path (in the form of File f), and you want to know if it is inside a particular folder (in the form of File cacheDir), you could simply traverse the chain of parent folders of your file and see if you meet the one you are looking for.
Like this:
public static boolean isCacheFile(File f) {
while (f.getParentDir()!=null) {
f = f.getParentDir();
if (f.equals(cacheDir)) {
return true;
}
}
return false;
}
boolean isContains(File directory){
File[] contents = directory.listFiles();
if (contents != null) {
for(int i = 0; i < contents.length; i++){
if(contents[i].isDirectory())
isContains(contents[i]);
else if(contents[i].getName().equals(*your_file_name*))
return true;
}
}
return false;
}
You could do it by recursion, by calling if the file exists in each sub-directory.
first check if the file exists in the root directory.
boolean exist = new File(rootDirectory, temp).exists();
then if the file wasn't in the root directory, then list all the files and call the method again in the sub-directoy files recursionally until you find the file or there are no more sub-directories.
public String getPathFromFileName(String dirToStart,Sring fileName){
File f = new File(dirToStart);
File[] list = f.listFiles();
String s="null";
for(int i=0;i<list.length;i++){
if(list[i].isFile()){
//is a file
if(fileName.equals(list[i])){
s=dirToStart+"/"+fileName;
break;
}
}else{
//is a directory search further.
getPathFromFileName(dirToStart+list[i]);
}
}
return s;
}
call this method by passing the parent directory name and the file name to search in subdirectories.
you check the return value if it is not equal to "null", then the files path is returned.

Deleting all files and folders in directory except hidden files using java

I need to delete all the files and folders in a directory but i need to .svn folder in this so that i can commit and delete the folder everytime. My below code worked but it retains .svn parent folder only but rest of its child .svn folders are deleted
my code:
if (pFile.exists() ) {
System.out.println(pFile.getName());
if (pFile.isDirectory()) {
if (pFile.list().length == 0) {
System.out.println("0>"+pFile.getName());
pFile.delete();
} else {
System.out.println("1>"+pFile.getName());
String[] strFiles = pFile.list();
for (String strFilename : strFiles) {
File fileToDelete = new File(pFile, strFilename);
System.out.println("2>"+fileToDelete.getName());
if(fileToDelete.getName()==".svn")
{
// Do Nothing
break;
}
else
{
delete(fileToDelete);
}
}
}
} else {
System.out.println("3>"+pFile.getName());
pFile.delete();
}
}
Need to modify condition as below. Here break will stop loop where as continue will skip only current deletion (ie, folder as .svn)
if(fileToDelete.getName()!=null && fileToDelete.getName().equals(".svn")){
// Do Nothing
continue;
}
You can use pFile.isHidden() to check if it is a hidden file.
In addition you can list all files in a folder with File.listFiles() instead of File.list() so you dont have to create a new File.
The other suggestions should solve your issue else you say, you need to delete all files and folders in a directory. So may be you are deleting all child folders that contain .svn in them and so you dont see them remain.

Search whole c drive for file type

Ok so part of my program searches the C drive for all mp3 files, the only problem is that it won't go into and subfolders. Here is my code so far.
public static List<String> ListFiles() {
List<String> files = new ArrayList<String>();
File folder = new File("C:/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile() && file.toString().contains(".mp3")) {
String fileS = file.getName();
files.add(fileS);
}
}
return files;
}
Try a recursive approach. The path is the current directory that you're in. Recursively call this on each folder and you will get to each file.
public void walk(String path) {
File root = new File(path);
File[] list = root.listFiles();
if (list == null) return;
for (File f : list) {
if (f.isDirectory()) {
walk(f.getAbsolutePath());
}
else {
//do what you want with files
}
}
}
Test whether file is a folder. If it is, pass it to ListFiles and append the return value to files.
For this to work, you need to change ListFiles to accept a File object as argument and start your search with this File instead of with "C:/"
Look into DirectoryStream<Path> class and the Files.isDirectory() method. Basically what you want to do is to check whether each Path is a file or directory.
If it is a directory, you call your method again. Else, you continue iterating.
Globbing is also possible with a directory stream. Saves you a lot of time instead of having to manually check file extensions.
If you wish to continue with your method or with directory stream, you will need to make a few modifications to your program to accomodate recursion.
If you want to do this yourself, you need to make it recursive. Which is what Oswald is getting at. A recursive method is a method that calls itself. So when you search a folder, for each element in it, if its an mp3, add it to the list, if its a folder, call your method again passing that folder in as the input.
I know it's Java question but why not just use Groovy and do it like:
static List<String> listMp3s() {
List<String> files = []
File rootFolder = new File('C:/')
rootFolder.eachFileRecurse(FileType.FILES) {
if (it.name.endsWith('.mp3')) {
files << it.name
}
}
return files
}

How to delete a file from a directory using Java?

Can anyone please tell me how to delete a file in a directory after being opened and loaded on to a database?
Here is my code:
public static void main(String[] args) throws SQLException{
int Count= 0;
File directory = new File("C://Documents and Settings//welcome//My Documents//Bluetooth Exchange Folder");
directory.deleteOnExit();
File files[] = directory.listFiles();
for(int index = 0; index < files.length; index++){
try {
FileReader inp = new FileReader (files[index]);
BufferedReader buf = new BufferedReader(inp);
String strLine;
try {
while ((strLine = buf.readLine()) != null)
{
System.out.println(strLine);
String[] dbColumnValues = strLine.split("%");
Connect.DoInsertIntoDB(Long.parseLong(dbColumnValues[0]),dbColumnValues[1],dbColumnValues[2], dbColumnValues[3]);
Count++;
System.out.println(Count + " Row(s) are inserted into the Database");
GenHTML.gen();
}
}
But the files are not deleted in the directory.
Please can anyone correct the mistake in my code?
[Currently, I am testing with 3 files in the directory. After each file gets loaded to the datbase, I want each files to get deleted from the directory.]
Thanks in advance!
It is better to be explicit in your code.
File files[] = directory.listFiles();
for(int index = 0; index < files.length; index++){
{
// Process files[index]
// ...
boolean wasDeleted = files[index].delete();
if (!wasDeleted)
{
// Deal with error
}
}
Also, you need to close your file handles when you are done with them
FileReader inp = new FileReader (files[index]);
try
{
// ...
}
finally
{
inp.close();
}
The File.delete() and File.deleteOnExit() methods will only delete a directory if it's empty. You'll have to delete the files from the directory as you process them (and make sure there are no subdirectories). Alternatively you can use FileUtils.deleteDirectory() from Apache Commons IO at the end of your processing.
The double slashes seems suspect. Either use a single backslash, which you need to quote as \\, or use a single slash /.
Also, you could try using delete() when then method returns instead of deleteOnExit().
According to the API:
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
In your code, however, you are treating that function as if it immediately deletes the directory.
You can't delete a directory, unless it's empty. If the directory is not empty, it is necessary to first recursively delete all files and subdirectories in the directory.
So directory.deleteOnExit() won't work in your case.
More, I suggest you to explicitly delete the files, not using deleteOnExit(). It is a dumb function that won't delete the file on exit if all the input/output streams related to the file are not closed. Always close the streams and explicitly delete the files, then the directory.
Maybe what you need to do is to use the dispose() method for the component that opens the file. What could possibly be the situation is that the file is still seen as opened and locked by a component that it had been opened in, so you have to ensure you use the dispose() method to solve that problem.

Categories