我正在使用java.util.Properties从属性文件加载属性。有没有办法在加载数据时自动删除值的空格? 目前我正在使用:
Properties properties = new Properties();
FileInputStream file = new FileInputStream(/path/to/file);
properties.load(file);
答案 0 :(得分:2)
您可以扩展Properties
类并覆盖其getProperty(String key)
方法以返回剪裁后的字符串。
public class MyProperties extends Properties {
@Override
public String getProperty(String key) {
return super.getProperty(key).trim();
}
}
使用它:
MyProperties properties = new MyProperties ();
FileInputStream file = new FileInputStream(/path/to/file);
properties.load(file);
//Now any propery you get will be returned trimmed
properties.getProperty("test"); //will be returned trimmed
答案 1 :(得分:0)
我得到的唯一可能的工作是,如果它对某些人有帮助,这不会影响已经存在的Properties类引用。
Properties properties = new Properties();
FileInputStream file = new FileInputStream(/path/to/file);
properties.load(file);
for (Entry<Object, Object> entry : properties.entrySet()) {
entry.setValue(entry.getValue().toString().trim());
}
答案 2 :(得分:0)
Properties config = new Properties();
String configFile = "config/apps.properties";
try (FileReader fr = new FileReader(configFile)) {
config.load(fr);
System.out.println(config);
for (String k : config.stringPropertyNames()) {
config.setProperty(k, config.getProperty(k).trim());
}
System.out.println(config);
} catch (IOException ex) {
System.out.printf("Error: Failed to load config file %s due to exception: %s\n", configFile, ex.toString());
System.exit(1);
}