2017-02-24 60 views
1

我想知道如何在jar文件啓動時創建文件? 其實我需要知道jar文件的確切路徑,並創建我的文件,如果它不存在 我試圖使用這個,但它在我的電腦和我的Windows服務器上有不同的結果!在java中啓動時創建文件

String path = MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 
    String decodedPath = URLDecoder.decode(path, "UTF-8").substring(1); 

事實證明我的反向電流路徑在我的電腦上,但事實證明「C:\」我的專用Windows服務器上

+2

Windows通常不會允許您寫入應用程序的目錄(假設它不在像'Users'這樣的可寫目錄中)。例如,如果你把你的jar放在Program Files中,你需要管理員權限才能在那裏寫入。好的做法是將文件寫入當前用戶的目錄。所有說,這個答案有什麼問題?(http://stackoverflow.com/questions/4032957/how-to-get-the-real-path-of-java-application-at-runtime) –

+0

所以如果我把我的jar文件從用戶文件夾中刪除,每件事情都應該正確嗎?也謝謝你回答我的第一個問題在計算器中:P – Peyman

+0

沒有。你的jar的位置應該不重要。它應該是便攜式的。 Windows用戶目錄(如'C:\ users \ someAccount')幾乎總是可寫的。答案提到它,但它是'System.getProperty(「user.home」);'。在Windows 10和Java 8上,這給了我'C:\ Users \ Chris' –

回答

0

這裏是你如何創建啓動文件,並將其放置在同一目錄該.jar:

private void createFile() throws Exception { 
    File currentDir = new File(Preferences.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); 
    prefs = new File(currentDir.getParentFile().getAbsoluteFile() + "/hackemos-prefs.txt"); 
    if(!prefs.exists()) { 
     prefs.createNewFile(); 

     String[] defaults = { 
       "9", // number of items 
       "100", // correct limit 
       "0", // amount to get wrong 
       "75", // delay, in ms 
       "456,278", // default mouse position for start button 
       "653,476", // default mouse position for copying text 
       "686,615", // default mouse position for the text box 
       "150,100", // Copy drag range 
       "0" // mac mode, 1 = enabled 
     }; 

     write(defaults); 
    } 
} 

這裏是你如何創建在啓動文件,並將其放置在Windows應用程序數據文件夾(用於堆放雜物的好地方),或在Linux/Mac的等價物。

public static void initDirs() { 
    String osName = Hardware.osName.toLowerCase(); 

    if(osName.contains("win")) { 
     gameDir = new File((System.getenv("APPDATA") + File.separator + "Hidden" + File.separator)); 
    } else if(osName.contains("mac")) { 
     gameDir = new File(System.getProperty("user.home") + "/Library/Application Support/Hidden"+File.separator); 
    } else if(osName.contains("nux")) { 
     gameDir = new File(System.getProperty("user.home")); 
    } 

    if(!gameDir.exists()) gameDir.mkdir(); 

    try { 
     FileOutputStream fos = new FileOutputStream(gameDir + File.separator + fileName); 
     ObjectOutputStream out = new ObjectOutputStream(fos); 
     out.writeObject(object); 
     out.close(); 
     fos.close(); 
     return true; 
    } catch(Exception e) { 
     e.printStackTrace(); 
     System.err.println("Couldn't save game."); 
     return false; 
    } 
} 

這只是我的一些舊程序的一些代碼。

+0

嗯,我得到的比我需要的更多。謝謝!它看起來像一個遊戲代碼:D我可以知道什麼遊戲? – Peyman

+0

沒問題!這裏是遊戲:https://www.youtube.com/watch?v=PkYXPXxMd7E&t=280s。雖然我很長一段時間都沒有開展過這項工作,但是我希望能夠在某個時候完成。 – wdavies973

相關問題