Solved

File exists?

Posted on 2002-04-13
2
215 Views
Last Modified: 2010-03-31
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?
0
Comment
Question by:jc31415
2 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 50 total points
ID: 6938978
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
 
LVL 16

Expert Comment

by:Peter Kwan
ID: 6938979
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

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now