Reputation: 16639
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?
Upvotes: 257
Views: 270566
Reputation: 772
If you want to check whether a file exists in your application's files:
File file = new File(getApplicationContext().getFilesDir(), "filename.txt");
if (file.exists()) {
// Do something
} else {
// Do something else
}
Upvotes: 32
Reputation: 344
if(new File("/sdcard/your_filename.txt").exists())){
// Your code goes here...
}
Upvotes: 3
Reputation: 47287
No file will be create when you make a File object, it is only an interface.
To make working with files easier, there is an existing .toFile
function on Uri
You can also add an extension property on File and/or Uri, to simplify usage further.
val File?.exists get() = this?.exists() ?: false
val Uri?.exists get() = File(this.toString).exists()
Then just use uri.exists
or file.exists
to check.
Upvotes: 0
Reputation: 31
public boolean FileExists(String fname) {
File file = getBaseContext().getFileStreamPath(fname);
return file.exists();
}
Upvotes: 2
Reputation: 6575
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.
Upvotes: 492
Reputation: 1500
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 ");
}
Upvotes: 5
Reputation: 6556
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
Upvotes: 34
Reputation: 2411
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
}
}
}
Upvotes: 10