Cas*_*tes 13 java string properties
我有一个Java Properties
对象,我从内存中String
加载,以前从实际.properties
文件加载到内存中,如下所示:
this.propertyFilesCache.put(file, FileUtils.fileToString(propFile));
Run Code Online (Sandbox Code Playgroud)
util fileToString
实际上从文件中读取文本,其余代码将其存储在HashMap
被调用的文件中propertyFilesCache
.后来,我从HashMap
as中读取文件文本String
并将其重新加载到Java Properties
对象中,如下所示:
String propFileStr = this.propertyFilesCache.get(fileName);
Properties tempProps = new Properties();
try {
tempProps.load(new ByteArrayInputStream(propFileStr.getBytes()));
} catch (Exception e) {
log.debug(e.getMessage());
}
tempProps.setProperty(prop, propVal);
Run Code Online (Sandbox Code Playgroud)
此时,我已经在我的内存属性文件中替换了我的属性,并且我想从Properties
对象中获取文本,就像我正在读取File
像上面所做的那样的对象.有没有一种简单的方法可以做到这一点,或者我将不得不迭代属性并String
手动创建?
lsi*_*siu 29
public static String getPropertyAsString(Properties prop) {
StringWriter writer = new StringWriter();
prop.list(new PrintWriter(writer));
return writer.getBuffer().toString();
}
Run Code Online (Sandbox Code Playgroud)
Ban*_*ana 11
@Isiu回答似乎有问题.在该代码之后,属性被截断,就像字符串长度有一些限制一样.正确的方法是使用这样的代码:
public static String getPropertyAsString(Properties prop) {
StringWriter writer = new StringWriter();
try {
prop.store(writer, "");
} catch (IOException e) {
...
}
return writer.getBuffer().toString();
}
Run Code Online (Sandbox Code Playgroud)
它与您的问题没有直接关系,但如果您只想打印出调试属性,可以执行以下操作
properties.list(System.out);
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 Java 8 或更高版本,这里是一个单语句解决方案,可以自己控制格式:
String properties = System.getProperties().entrySet()
.stream()
.map(e -> e.getKey() + ":" + e.getValue())
.collect(Collectors.joining(", "));
Run Code Online (Sandbox Code Playgroud)