0

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Seephor
  • 1,692
  • 3
  • 28
  • 50
  • 1
    Can you show us the directory structure ? – AllTooSir May 06 '13 at 17:11
  • /dev/app/build is what I get when I print System.getProperty(user.dir) - I want a file inside /dev/app/web/main – Seephor May 06 '13 at 17:12
  • 1
    What is the absolute path of `new.txt`? – durron597 May 06 '13 at 17:12
  • @Seephor if your `new.txt` is in root folder then you dont need `../`. – Smit May 06 '13 at 17:16
  • 4
    print `nFile.getAbsolutePath()` and `new File("").getAbsolutePath()` and you'll see what's wrong. The later will print the working directory. See if `dir` is really the parent of `new.txt`, also you could use [File(String parent, String child)](http://docs.oracle.com/javase/6/docs/api/java/io/File.html#File(java.lang.String,%20java.lang.String)) for creating `nFile` – A4L May 06 '13 at 17:17
  • nFile prints: "C:\dev\app\build\..\web\main" and the ("") file prints "C:\dev\app\build". I am trying to create a file in \dev\app\web\main – Seephor May 06 '13 at 17:33
  • as suggested by @A4L, File(String parent, String child) should work for you, probably with file.getParentFile() – Alex Turbin May 06 '13 at 18:04

2 Answers2

1

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.

A4L
  • 17,353
  • 6
  • 49
  • 70
0

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]
desperateCoder
  • 700
  • 8
  • 18
  • System.getProperty(user.dir) gives me a path like /dev/app/build, but I want a file in /dev/app/web/main – Seephor May 06 '13 at 17:16
  • so you start your application from /dev/app/build? you could / should use an starter anyway, so you can create a shellscript starting something like: "java -jar web/main/program.jar" – desperateCoder May 06 '13 at 17:18