在java

时间:2017-02-24 17:03:50

标签: java

我想知道如何在jar文件启动时创建文件? 实际上我需要知道jar文件的确切路径并创建我的文件(如果它尚不存在) 我试图使用它,但它在我的电脑和我的Windows服务器上有不同的结果!

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

它让我回到计算机上的当前路径,但它变成了#34; C:\"在我的专用Windows服务器上

1 个答案:

答案 0 :(得分: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 appdata文件夹(保存内容的好地方)或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;
    }
}

这只是我以前的一些程序中的一些代码。