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?
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 as parent. The above code does not handle this case.
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.