【发布时间】:2013-09-19 22:24:38
【问题描述】:
我将 java 属性 user.dir 设置为 /home/alex/projects/poltava/rpgu/workingdir。我也有文件 q.txt 在上面的文件夹中。
下面是sn-ps的代码及其返回值(=之后):
System.getProperty("user.dir") = /home/alex/projects/poltava/rpgu/workingdir
new File(".").getAbsolutePath() = /home/alex/projects/poltava/rpgu/workingdir/.
new File(".").exists() = true
new File("q.txt").getAbsolutePath() = /home/alex/projects/poltava/rpgu/workingdir/q.txt
new File("q.txt").exists() = false
new File(new File("q.txt").getAbsolutePath()).exists() = true
new FileInputStream("q.txt") = threw FileNotFoundException
这样您就可以看到文件确实存在于文件系统中。当我尝试使用绝对路径获取它时,一切都很好。当我尝试使用相对路径获取它时,它失败了。
相对路径有什么问题?
已编辑:
演示问题的小应用程序:
import java.io.File;
public class Test {
public static void main(String[] args) {
System.setProperty("user.dir", "/home/alex/projects/poltava/rpgu/workingdir");
System.out.println(System.getProperty("user.dir"));
System.out.println(new File("q.txt").exists());
System.out.println(new File("q.txt").isFile());
System.out.println(new File("q.txt").canRead());
System.out.println(new File("q.txt").getAbsolutePath());
System.out.println(new File(new File("q.txt").getAbsolutePath()).exists());
System.out.println(new File(new File("q.txt").getAbsolutePath()).isFile());
System.out.println(new File(new File("q.txt").getAbsolutePath()).canRead());
try {
new FileInputStream("q.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
输出:
/home/alex/projects/poltava/rpgu/workingdir
false
false
false
/home/alex/projects/poltava/rpgu/workingdir/q.txt
true
true
true
java.io.FileNotFoundException: q.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at Test.main(Test.java:24)
编辑 2:
我还尝试了另一个简单的例子:
File f = new File("q1.txt");
System.out.println(f.createNewFile());
System.out.println(f.getPath());
System.out.println(f.getAbsolutePath());
输出:
true
q1.txt
/home/alex/projects/poltava/rpgu/workingdir/q1.txt
结果文件是在我启动应用程序的目录中创建的。不在user.dir 目录中。而getAbsolutePath() 返回的文件路径不正确。
【问题讨论】:
-
您能否提供完成所有日志记录和测试的代码,以便我们自己更轻松地进行测试?
-
示例代码已添加。
-
这两种情况都可以打印 file.getPath() 吗?似乎有一个内部为字符串调用的解析方法,getPath 将打印而不解析任何内容。
-
q.txt和/home/alex/projects/poltava/rpgu/workingdir/q.txt分别