Ubuntu上的File.getAbsolutePath不正确

时间:2012-11-21 22:07:14

标签: java file ubuntu netbeans path

这是this one的后续问题(就像一个简短的描述:我已经能够通过双击OS X和Windows上的.jar文件来运行Java程序,但不是在Linux上,因为后者我遇到文件路径问题。)

通过在Ubuntu(12.04)下使用NetBeans尝试一些事情,我发现问题似乎位于程序认为的工作目录中(我从File.getAbsolutePath()的输出中得出结论)。如果我在NetBeans中启动我的应用程序,一切正常(甚至在Ubuntu下)和

System.out.println(new File(".").getAbsolutePath());

给了我/home/my_home/projects/VocabTrainer/.,这是我的项目文件夹,因此是正确的。但是,如果我双击位于.jar的{​​{1}}文件,我在Ubuntu下的输出突然只是/home/my_home/projects/VocabTrainer/dist这是有问题的,因为我想访问一个数据文件位于我的/home/my_home/.目录的子目录中。

有谁知道这种行为的原因,以及我如何解决这个问题?

PS:我不知道这是否是必需的,但这里是dist的输出

java -version

2 个答案:

答案 0 :(得分:2)

我认为您将JAR的位置与current working directory混淆。

要确定前者,请参阅How to get the path of a running JAR file?

答案 1 :(得分:1)

目前的原因并非如此。但由于明显的不可预测性,您可能不希望以这种方式处理它。这样的东西应该得到文件,假设你在下面的getResource调用中使用jar中某些东西的限定类名。:

URL url = this.getClass().getClassLoader().getResource("thepackage/ofyourclass/JunkTest.class");  //get url of class file.  expected: ("jar:file:/somepath/dist/yourjar.jar!qualified/class/name.class")
File distDir = null;
if(url.getProtocol() == "jar") {
    String classPath = null;
    String jarPath = url.getPath();
    if(jarPath.matches(".*:.*")) jarPath = new URL(jarPath).getPath();
    classPath = jarPath.split("!")[0];
    distDir = new File(classPath).getParentFile(); //may need to replace / with \ on windows?
} else { //"file" or none
    distDir = new File(url.toURI()).getParentFile();
}    
//... do what you need to do with distDir to tack on your subdirectory and file name
编辑:我应该指出这显然是hacky。您可以在启动时直接将文件的位置添加到类路径中(或者包含您在jar中查找的文件)。从这里你可以使用this.getClass().getClassLoader().getResource()直接找到你想要的文件名,这会让你得到类似的东西:

URL url = this.getClass().getResource("yourfile");
File file = new File(url.toURI());
//... use file directly from here

进一步编辑:好的,适应你缺少的协议,并将其展开,所以错误消息对你来说更具可读性。