Tuesday 8 April 2014

Check if a file exists using Java

I have long thought about including some content about Core Java concepts on my blog. So here is one of the first ones in the series, which covers some basic Java fundamentals. I assume you have some knowledge about using the Eclipse IDE for project creation. I also assume that you have some basic idea about the Java language (theoretical concepts like OOPS, Inheritance, Data abstraction etc). Don't worry if you don't know much because I plan to cover a few posts on those basics later.

At this point, this post here is all about writing a simple script in Java for checking if a specific file exists at a certain location. You may use the following example for quick reference.

Briefly speaking, we would be importing the java.io.File class and use one of it's methods - isFile.

Please note that the best preferred function to check if a files exists is exists(). In this example, we see how isFile() can also be used to check the same.

Here we go - Create a new class file in Eclipse named as "CheckFileExists_Example". If you maybe aware, the class name and filename has to be the same in Java.

package my.ironcladzone.com;

import java.io.IOException;
import java.io.File;

public class CheckFileExists_Example {

    public static void main(String[] args) {
            
            File f = new File("/usr/tmp/DocuTest.txt");
           
            if (f.isFile()) {
               
                System.out.println("File exists \n");
               
            } else {
       
                System.out.println("File does not exist \n");
            }
     }

}

Here, the method isFile is used to check if "DocuTest.txt" is a file or not. It returns a boolean value - true or false, depending on whethere it actually is a file or not. It will return false if the absolute path mentioned by us, turns out to be a directory.

Play around with code and check for yourself. Edit the path as just :

File f = new File("/usr/tmp/");

Now, the isFile function returns false since the path mentions the '/usr/tmp' location, which is a directory and not a file. So it will directly jump to the else block and print our "File does not exist" statement.

Try one more scenario - specify an imaginary filename in the path. Let's say for example xyz123.txt.

File f = new File("/usr/tmp/xyz123.txt");

It will return false if a filename xyz123.txt does not exist at a specific location.

The point here is how isFile() function can also be used, instead of traditional exists() function for checking if a specific filename exists. It serves a same-to-similar purpose.

I'd cover some more basic topics on I/O in Java i.e reading from files, writing to files in some future posts. So, stay tuned folks. In the meantime, do post your comments for any suggestions & tips. Ciao.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
eXTReMe Tracker