因此,您希望将与 main/runnable jar 位于同一文件夹中的 .properties 文件视为文件而不是 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
因此,当您从根/基本文件夹运行主程序时,通常您会像这样运行它:
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
*/
import java.util.Properties;
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();
}