File exists?

What is the easiest way within my JAVA program to find out if a file (myFile.txt) exists in the current directory or (not as important to me) in any directory?
jc31415Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
CEHJConnect With a Mentor Commented:
File f = new File("myFile.txt");
boolean fileExists = f.exists();

If you want to check if it exists anywhere on the HD, you'll have to recurse all directories on each drive
0
 
Peter KwanAnalyst ProgrammerCommented:
To check whether a file exists in the current directory, here is an example:

import java.io.*;

public class FileTest {
   public static void main(String[] args) {
       try {
          File f = new File("myFile.txt");

          if (f.exists())
             System.out.println("Exists");
          else
             System.out.println("Not exists");
        } catch (Exception e) { }
   }
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.