2017-02-24 80 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

相关问题