[英]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.