Nei*_*eil 119 java properties
我有一个JAR文件,我的所有代码都存档以便运行.我必须访问每次运行前需要更改/编辑的属性文件.我想将属性文件保存在JAR文件所在的目录中.有没有告诉Java从该目录中获取属性文件?
注意:我不想将属性文件保留在主目录中,也不希望在命令行参数中传递属性文件的路径.
ecl*_*cle 135
因此,您希望将.properties与main/runnable jar相同的文件夹中的文件视为文件,而不是作为main/runnable jar的资源.在这种情况下,我自己的解决方案如下:
首先要做的是:你的程序文件架构应该是这样的(假设你的主程序是main.jar,它的主要属性文件是main.properties):
./ - the root of your program
|__ main.jar
|__ main.properties
Run Code Online (Sandbox Code Playgroud)
使用此体系结构,您可以在main.jar运行之前或期间使用任何文本编辑器修改main.properties文件中的任何属性(取决于程序的当前状态),因为它只是基于文本的文件.例如,您的main.properties文件可能包含:
app.version=1.0.0.0
app.name=Hello
Run Code Online (Sandbox Code Playgroud)
因此,当您从其root/base文件夹运行主程序时,通常您将按以下方式运行它:
java -jar ./main.jar
Run Code Online (Sandbox Code Playgroud)
或者,马上:
java -jar main.jar
Run Code Online (Sandbox Code Playgroud)
在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;
}
Run Code Online (Sandbox Code Playgroud)
在需要该app.version值的主程序的任何部分中,我们将其方法称为如下:
String version = null;
try{
version = getAppVersion();
}
catch (IOException ioe){
ioe.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
Nin*_*ale 38
我通过其他方式做到了.
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
168766 次 |
| 最近记录: |