如何在.property文件中保存参数值?

时间:2013-02-23 10:31:36

标签: java jquery jsp url servlets

如何在jsp

中的.properties文件中保存参数值及其值,如键值对

对于例如。
网址: http://www.xyz.com/login.jsp FNAME =哈里&安培; L-NAME = POTTER&安培;职业=演员

.property文件必须如下所示
fname =哈里
L-NAME =陶工
职业=演员

有可能吗?

提前致谢

2 个答案:

答案 0 :(得分:2)

这个怎么样:

final String urlString = "http://www.xyz.com/login.jsp?fname=harry&lname=potter&occupation=actor";
final URL url;
try {
    url = new URL(urlString);
} catch (MalformedURLException ex) {
    throw new RuntimeException(ex);
}
final Properties properties = new Properties();
for (final String param : url.getQuery().split("\\&")) {
    final String[] splitParam = param.split("=");
    properties.setProperty(splitParam[0], splitParam[1]);
}
for (final String key : properties.stringPropertyNames()) {
    System.out.println("Key " + key + " has value " + properties.getProperty(key) + ".");
}
final FileOutputStream fileOutputStream;
try {
    fileOutputStream = new FileOutputStream(new File("My File"));
} catch (FileNotFoundException ex) {
    throw new RuntimeException(ex);
}
try {
    properties.store(fileOutputStream, "Properties from URL '" +urlString + "'.");
} catch(IOException ex) {
    throw new RuntimeException(ex);
} finally {
    try {
        fileOutputStream.close();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

}

这将解析URL并将params放入Properties对象,然后将其写入文件。

请注意,如果您的URL字符串中有任何重复的键,它们将被覆盖,因此此方法不起作用。在这种情况下,您可能需要查看Apache HttpComponents

答案 1 :(得分:1)

检查java.util.Properties.store(OutputStream, String)java.util.Properties.store(Writer, String)(Java 1.6)