How to see if a file exists in Java (IN THE CURRENT DIRECTORY)

twitter logo github logo ・1 min read

It's nice to see some of my followers, and other lingerers here, and thanks for reading.
So I am making an app builder in java, and I googled

How to see if a file exists in java

and I on StackOverflow I see answers like:

File f = new File(filename); //in my case: "Built Applications/New Application"

but when I do this it returns false every time.
When I get the absolute path, it returns:

"C:\Users\calin\Built Applications\New Application"

but I need it to be relative, which should return:

"C:\Users\calin\OneDrive\Desktop\java projects\misc\AppBuilder\Built Applications\New Application"

how can I do this?
Thanks, and

twitter logo DISCUSS (5)
markdown guide

You'll need to specify the parent directory. Something like (note the backslash-escaped backslashes):

File parent = new File("C:\\Users\\calin\\OneDrive\\Desktop\\java projects\\misc\\AppBuilder");
File f = new File(parent, "Built Applications\\New Application");

should do what you want. If you want to avoid the backslashes (and escaping), build up the parent starting with the value of the "user.home" system property.

(Note: Original post had a think-o where I used "java.home" instead of the correct "user.home".)


Ok, but that's just for my case, what if I want to get a parent directory for anyone who is using this software? that's what I was looking for :/


I suggest you start the java.lang.System property "user.home" if it is a per-user value:

File home = new File(System.getProperty("user.home"));
File parent = new File(home, "blah ... BuiltApplications");
File file = new File(parent, filename); // filename from your original example


Would something like this work? Get cwd, then add your directory to it by concatenation.

Classic DEV Post from Feb 26

You're Not An Impostor

Hey you. Yes, you, the reader. You clicked on this article because you have som...

PDS OWNER CALIN (Calin Baenen) profile image
I am a 12 yr/o developer who makes projects in languages like: Java, HTML, Python, JS, CSS, C, and am working on learning C++, and C#.

Do you prefer sans serif over serif?

You can change your font preferences in the "misc" section of your settings. ❀️