2012-06-05 107 views
0

Bellow是我的代碼,當我在IDE中運行這些代碼時它運行良好,但是當我在dos命令中運行時,它給了我一個NullPointException的錯誤。請給我一個手。 謝謝!爲什麼getResource會給出不同的結果?

 //first get the classLoader 
    ClassLoader classLoader = TestMainPath.class.getClassLoader(); 
    //show message 
    System.out.println("loader=" + classLoader); 
    // 
    URL r = classLoader.getResource("TestMainPath/TestMainPath.class"); 
    System.out.println("r=" + r); 
    String mainPath =r.getPath(); 
    System.out.println(mainPath); 
    File sf = new File(mainPath + "/main/newfile"); 
    System.out.println(sf.getPath()); 
    System.out.println(sf.exists()); 
+2

哪一行有NullPointerException? –

+2

我認爲你得到'NullPointerException'的那一行是:'String mainPath = r.getPath()' - 這表明類加載器沒有找到這個文件。這可能是類路徑問題。 – Xeon

回答

4

您的問題只是因爲您的IDE不像您那樣啓動應用程序。在你的情況下,差異在類路徑上。 檢查IDE如何啓動程序,使用哪個類路徑。同時驗證您的類文件是否真的是您從命令行啓動時所期望的位置。

相關問題