[英]how to read property files from external storage
我有一个从控制台运行的 jar 文件。 在程序本身中,我必须从属性文件中读取数据,该文件应该与我的 jar 文件位于同一文件夹中。 我怎样才能做到这一点?
我的代码无法正常工作:
public class ReadProperties {
String propPath = System.getProperty("app.properties");
private String message;
private String userName;
ReadProperties() {
readProperties();
}
private void readProperties() {
final FileInputStream in;
try {
in = new FileInputStream(propPath);
Properties myProps = new Properties();
myProps.load(in);
message = myProps.getProperty(Constants.MESSAGE);
userName = myProps.getProperty(Constants.USERNAME);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getMessage() {
return message;
}
public String getUserName() {
return userName;
}
}
请注意,您在上面编码的方式需要一个系统属性来标记要加载的文件,传递为:
java -Dapp.properties=somefile.properties
如果您想要一个名为“app.properties”的文件,则需要更改propPath
的声明而不使用System.getProperty
您的文件处理应该使用 try 和资源在之后通过自动关闭进行清理,而不是隐藏任何异常:
try (FileInputStream in = new FileInputStream(propPath)) {
// load here
}
您可以在异常之后提供默认属性值,或者通过将throws IOException
添加到方法来处理,或者 append 代码以适应运行时异常,以便报告:
catch (Exception e) {
throw new UncheckedIOException(e);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.