2012-11-21 28 views
1

這是對this one的後續問題(就像一個簡單的描述:我已經能夠通過雙擊OS X和Windows上的.jar文件運行Java程序,但不能在Linux上,與後者一樣,我得到一個文件路徑問題)。Ubuntu上的File.getAbsolutePath不正確

通過在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) 

回答

1

的原因,不是真的,此刻。但由於明顯的不可預測性,您可能不想這樣處理。像這樣的東西應該得到的文件,假設你的罐子在下面的getResource電話:

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 

編輯使用的一些合格的類名:我應該指出,這顯然是哈克。您可以在啓動時直接將文件的位置添加到類路徑中(或者在jar中包含您要查找的文件)。從這裏就可以使用this.getClass().getClassLoader().getResource()與你直接找什麼文件名,這將讓你喜歡的東西:

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

進一步編輯:好,適應您遺漏協議,並宣揚出去,所以錯誤消息對你來說會更具可讀性。

+0

感謝您的回覆!我可能做了些傻事(我是Java新手......),但是URL「url = this.getClass()。getClassLoader()。getResource(」qualified/class/VocabItem.class「);」給了我url == null。我只是選了我的一個班的名字,但也許我誤解了你的建議! – canavanin

+0

啊 - 假設你有一個類,用相關類的包替換「qualified/class」位。一個類的「合格類名」是該包預先定義的類名。爲此,您需要交換「。」字符爲「/」。所以,如果你的VocabItem類在com.canavanin包中,你可以使用「com/canavanin/VocabItem.class」作爲該字符串。如果沒有包,則應該可以省略該部分字符串。 –

+0

感謝您的更新。現在我得到一個MalformedURLExeption:java.net.MalformedURLException:沒有協議:/home/my_home/projects/VocabTrainer/build/classes/my/vocabtrainer/VocabItem.class – canavanin

相關問題