MBH
MBH

Reputation: 16639

Android; Check if file exists without creating a new one

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

Answers (8)

Jordi Vicens
Jordi Vicens

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

Isira Adithya
Isira Adithya

Reputation: 344

if(new File("/sdcard/your_filename.txt").exists())){
              // Your code goes here...
}

Upvotes: 3

Gibolt
Gibolt

Reputation: 47287

Kotlin Extension Properties

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

HomieZ2
HomieZ2

Reputation: 31

public boolean FileExists(String fname) {
        File file = getBaseContext().getFileStreamPath(fname);
        return file.exists();
}

Upvotes: 2

Maikel Bollemeijer
Maikel Bollemeijer

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

Anand Dwivedi
Anand Dwivedi

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

Victor Laerte
Victor Laerte

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

thomas8wp
thomas8wp

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

Related Questions