Android; Check if file exists without creating a new one
Solution 1
Your chunk of code does not create a new one, it only checks if its already there and nothing else.
File file = new File(filePath);
if(file.exists())
//Do something
else
// Do something else.
Solution 2
When you use this code, you are not creating a new File, it's just creating an object reference for that file and testing if it exists or not.
File file = new File(filePath);
if(file.exists())
//do something
Solution 3
It worked for me:
File file = new File(getApplicationContext().getFilesDir(),"whatever.txt");
if(file.exists()){
//Do something
}
else{
//Nothing
}
Solution 4
When you say "in you package folder," do you mean your local app files? If so you can get a list of them using the Context.fileList() method. Just iterate through and look for your file. That's assuming you saved the original file with Context.openFileOutput().
Sample code (in an Activity):
public void onCreate(...) {
super.onCreate(...);
String[] files = fileList();
for (String file : files) {
if (file.equals(myFileName)) {
//file exits
}
}
}
Solution 5
The methods
in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file
system to verify that a particular Path exists
File file = new File("FileName");
if(file.exists()){
System.out.println("file is already there");
}else{
System.out.println("Not find file ");
}
Related videos on Youtube
![MBH](https://i.stack.imgur.com/qdoxr.jpg?s=256&g=1)
MBH
Software Engineer, Addicted to writing Mobile Applications for both platforms Android and iOS.
Updated on June 26, 2021Comments
-
MBH about 3 years
I want to check if file exists in my package folder, but I don't want to create a new one.
File file = new File(filePath); if(file.exists()) return true;
Does this code check without creating a new file?
-
piokuc about 11 yearspossible duplicate of Test if file exists
-
Remi Guan over 8 years@Kunok I'm checking your edit comment: removed words such as tanks as they are... :P
-
Kunok over 8 years@KevinGuan Oh yeah my bad, just got home from new eve party so I was not able to write properly :)
-
-
ofnowhere over 10 yearsDont know why in my case this code is creating a new file.
-
Pratik Butani about 10 yearsHow to check in sub folder also?
-
Giova over 9 yearsThis is like that because there is no static method : File.exists(String file) , so you have to instanciate a new File object to access 'Exists' method.
-
AndroDev almost 8 yearsI think OP doesn't wish to create new file object.
-
Zach almost 5 yearsThis is the solution if you only have the file name and not its path
-
Jordi Vicens almost 5 years@Zach Not really, it's path would be the first parameter I sent ( getApplicationContext().getFilesDir() )
-
Marian Paździoch about 4 years@AndroDev no - he doesn't wish to create new FILE, answer creates new REFERENCE to file.
-
dbc about 4 years