问题

我有一个JAR文件,我的所有代码都存档以便运行。我必须访问每次运行前需要更改/编辑的属性文件。我想将属性文件保存在JAR文件所在的目录中。有没有告诉Java从该目录中获取属性文件?

注意:我不想将属性文件保留在主目录中,也不希望在命令行参数中传递属性文件的路径。


#1 热门回答(118 赞)

因此,你希望将main.properties文件作为主/ runnable jar作为文件而不是main / runnable jar的资源处理。在这种情况下,我自己的解决方案如下:

首先要做的是:你的程序文件架构应该是这样的(假设你的主程序是main.jar,它的主要属性文件是main.properties):

./ - the root of your program
 |__ main.jar
 |__ main.properties

使用此体系结构,你可以在main.jar运行之前或期间使用任何文本编辑器修改main.properties文件中的任何属性(取决于程序的当前状态),因为它只是一个基于文本的文件。例如,你的main.properties文件可能包含:

app.version=1.0.0.0
app.name=Hello

因此,当你从其root / base文件夹运行主程序时,通常你将按以下方式运行它:

java -jar ./main.jar

或者,马上:

java -jar main.jar

在main.jar中,你需要为main.properties文件中的每个属性创建一些实用程序方法;假设app.version属性将具有如下的getAppVersion()方法:

/**
 * Gets the app.version property value from
 * the ./main.properties file of the base folder
 *
 * @return app.version string
 * @throws IOException
 */
public static String getAppVersion() throws IOException{

    String versionString = null;

    //to load application's properties, we use this class
    Properties mainProperties = new Properties();

    FileInputStream file;

    //the base folder is ./, the root of the main.properties file  
    String path = "./main.properties";

    //load the file handle for main.properties
    file = new FileInputStream(path);

    //load all the properties from this file
    mainProperties.load(file);

    //we have loaded the properties, so close the file handle
    file.close();

    //retrieve the property we are intrested, the app.version
    versionString = mainProperties.getProperty("app.version");

    return versionString;
}

在需要app.version值的主程序的任何部分中,我们将其方法称为如下:

String version = null;
try{
     version = getAppVersion();
}
catch (IOException ioe){
    ioe.printStackTrace();
}

#2 热门回答(30 赞)

我通过其他方式做到了。

Properties prop = new Properties();
    try {

        File jarPath=new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        String propertiesPath=jarPath.getParentFile().getAbsolutePath();
        System.out.println(" propertiesPath-"+propertiesPath);
        prop.load(new FileInputStream(propertiesPath+"/importer.properties"));
    } catch (IOException e1) {
        e1.printStackTrace();
    }

-获取Jar文件路径。

  • 获取该文件的Parent文件夹。
  • 在InputStreamPath中使用该路径和你的属性文件名。

#3 热门回答(1 赞)

从jar文件访问文件目录中的文件始终存在问题。在jar文件中提供类路径非常有限。而是尝试使用bat文件或sh文件来启动程序。通过这种方式,你可以随意指定类路径,引用系统中任何位置的任何文件夹。

另请查看我对这个问题的回答:
making .exe file for java project containing sqlite


原文链接