Seephor
Seephor

Reputation: 1732

relative file path not working in Java

After reading that is it possible to create a relative filepath name using "../" I tried it out.

I have a relative path for a file set like this:

String dir = ".." + File.separator + "web" + File.separator + "main";

But when I try setting the file with the code below, I get a FileNotFoundException.

File nFile= new File(dir + File.separator + "new.txt");

Why is this?

Upvotes: 0

Views: 1077

Answers (2)

A4L
A4L

Reputation: 17595

nFile prints: "C:\dev\app\build\..\web\main"

and

("") file prints "C:\dev\app\build"

According to your outputs, after you enter build you go up 1 time with .. back to app and expect web to be there (in the same level as build). Make sure that the directory C:\dev\app\web\main exists.

You could use exists() to check whether the directory dir exist, if not create it using mkdirs()

Sample code:

File parent = new File(dir);
if(! parent.exists()) {
    parents.mkdirs();
}
File nFile = new File(parent, "new.txt");

Note that it is possible that the file denoted by parent may already exist but is not a directory, in witch case it would not be possible to use it a s parent. The above code does not handle this case.

Upvotes: 1

desperateCoder
desperateCoder

Reputation: 700

Why wont you take the Env-Varable "user.dir"?

It returns you the path, in which the application was started from.

System.getProperty(user.dir)+File.separator+"main"+File.separator+[and so on]

Upvotes: 0

Related Questions