简体   繁体   English

相对文件路径在Java中不起作用

[英]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 . 但是,当我尝试使用以下代码设置文件时,出现FileNotFoundException

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

Why is this? 为什么是这样?

nFile prints: "C:\\dev\\app\\build\\..\\web\\main" nFile打印:“ C:\\ dev \\ app \\ build \\ .. \\ web \\ main”

and

("") file prints "C:\\dev\\app\\build" (“”)文件打印“ 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 ). 根据您的输出,输入build之后,您将用..移1次回到app并期望web在那里(与build处于同一级别)。 Make sure that the directory C:\\dev\\app\\web\\main exists. 确保目录C:\\dev\\app\\web\\main存在。

You could use exists() to check whether the directory dir exist, if not create it using mkdirs() 您可以使用exist ()检查目录dir是否存在,如果不使用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. 请注意,以parent表示的文件可能已经存在但不是目录,在这种情况下,将其用作父文件是不可能的。 The above code does not handle this case. 上面的代码无法处理这种情况。

Why wont you take the Env-Varable "user.dir"? 您为什么不选择Env变量“ 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM