這裏是你如何創建啓動文件,並將其放置在同一目錄該.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;
}
}
這只是我的一些舊程序的一些代碼。
Windows通常不會允許您寫入應用程序的目錄(假設它不在像'Users'這樣的可寫目錄中)。例如,如果你把你的jar放在Program Files中,你需要管理員權限才能在那裏寫入。好的做法是將文件寫入當前用戶的目錄。所有說,這個答案有什麼問題?(http://stackoverflow.com/questions/4032957/how-to-get-the-real-path-of-java-application-at-runtime) –
所以如果我把我的jar文件從用戶文件夾中刪除,每件事情都應該正確嗎?也謝謝你回答我的第一個問題在計算器中:P – Peyman
沒有。你的jar的位置應該不重要。它應該是便攜式的。 Windows用戶目錄(如'C:\ users \ someAccount')幾乎總是可寫的。答案提到它,但它是'System.getProperty(「user.home」);'。在Windows 10和Java 8上,這給了我'C:\ Users \ Chris' –