繁体   English   中英

Ubuntu上的File.getAbsolutePath不正确

[英]File.getAbsolutePath incorrect on Ubuntu

这是对此问题的后续问题(仅作为简要说明:我已经能够通过双击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/. ,这是我的项目文件夹,因此是正确的。 但是,如果我双击位于/home/my_home/projects/VocabTrainer/dist.jar文件,我在Ubuntu下输出的输出突然只是/home/my_home/. 这是有问题的,因为我想访问位于我的dist目录的子目录中的数据文件。

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

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

java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.5) (6b24-1.11.5-0ubuntu1~12.04.1)
OpenJDK Server VM (build 20.0-b12, mixed mode)

我认为你把JAR的位置与当前的工作目录混淆了。

要确定前者,请参阅如何获取正在运行的JAR文件的路径?

目前的原因并非如此。 但由于明显的不可预测性,您可能不希望以这种方式处理它。 这样的东西应该得到文件,假设你在下面的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

进一步编辑:好的,适应您丢失的协议,并将其展开,因此错误消息对您来说更具可读性。

暂无
暂无

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

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