我有一个JNLP,其中我向主应用程序提供了一些参数。
我想以一种可移植(至少是Windows/Linux)的方式给出用户主目录的一个子目录作为参数。
我试着看一下${user。,但我真的不知道JNLP是否会执行替换。
编辑
说明一下:我不需要在客户端机器上存储或查找某些属性的方法。我需要一种方法通过包含用户主目录的JNLP传递参数。这显然至少可以在Windows和Linux平台上工作。为了实现这个目标,我只想读取系统属性"user"。home",由JVM设置。但是,我认为Java Web Start可以在客户端执行一些替换。
确实,所需的参数可以是相对于用户的主目录,我的应用程序可以只加载system属性。然而,有一些用例,当我不希望这种行为。
我只是想用一种独立于平台的方式来指定用户的主目录…
web服务器在jnlp文件中自动替换的唯一值是:
- $$codebase-请求的URL,除了JNLP文件的名称
- $$name JNLP文件的名称
- $$context web应用程序的基础URL
- $$site web服务器地址
- $$hostname服务器名
这些替换只有在servlet容器中使用JNLPDownloadServlet时才会发生。
主机在下载JNLP文件时不可能知道user home参数的值。
如果您正在部署一个可以独立运行的JNLP,并且您需要将参数加载到应用程序中,我建议在文件不存在时在特定位置使用默认值属性文件(应用程序可以在第一次运行时动态创建属性文件,或者您可以使用安装程序来这样做)。
下面是一个详细的例子:
public class Main {
public static void main(String ... args) throws IOException{
new Main();
}
private static Properties instance;
public static Properties getProperties(){
return instance;
}
private static Properties defaultProperties(){
// implement default properties here
Properties props = new Properties();
props.setProperty("myApp.property1","someDefaultValue");
return props;
}
public static void createDefaultPropsFile(File propsFile,Properties props) throws IOException {
propsFile.getParentFile().mkdirs();
props.store(new FileWriter(propsFile),"My App Properties");
}
private Main() throws IOException{
File appDir = new File(System.getProperty("user.home"), "myApp");
// find property file
File propsFile = new File(appDir, "settings.properties");
Properties appProperties = new Properties(defaultProperties());
if(!propsFile.exists()){
createDefaultPropsFile(propsFile,appProperties);
} else {
appProperties.load(new FileReader(propsFile));
}
// this should really be done using a singleton or something similar
instance = appProperties;
System.out.println("Property"+getProperties().getProperty("myApp.property1"));
}
}
谢谢您的回答,但是我不能在用户目录中存储属性。我只是希望参数列表是可移植的,这样总能找到用户的主目录。
我的解决方案并不完美,它只是遵循Apache的Ant方式:用系统属性中的相应值替换出现的${myvariable}。
代码如下:
public class PropertySubstitutor {
private static final Pattern VARIABLE_PATTERN = Pattern.compile("\$\{(.*?)\}");
public static String substitute(String source) {
Matcher matcher = VARIABLE_PATTERN.matcher(source);
Properties properties = System.getProperties();
StringBuffer buffer = new StringBuffer(source.length());
while (matcher.find()) {
matcher.appendReplacement(buffer, properties.getProperty(matcher.group(1), ""));
}
matcher.appendTail(buffer);
System.out.println(buffer.toString());
return buffer.toString();
}
private PropertySubstitutor() {}
}
可以将此帮助器更改为使用用户定义的属性对象。
我使用慢速的regexp引擎,因为我只需要在应用程序启动时解析两个或两个参数。
如果您重定向桌面- Java 7及以下似乎设置了用户。家里不正确。例如,与%userprofile%不一致。