Java Properties对象为String

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.后来,我从HashMapas中读取文件文本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)

  • 值得注意的是,这将不会让您直接渲染属性,即您不能将该字符串弹出到文件中并将其作为属性文件加载回来.这是因为**Properties.list()**方法将一个标题添加到列表中:` - 列出属性 - 更可能你想要使用**中描述的**Properties.store()**方法来自@joev评论的评论如下. (4认同)

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)


mae*_*tr0 8

它与您的问题没有直接关系,但如果您只想打印出调试属性,可以执行以下操作

properties.list(System.out);
Run Code Online (Sandbox Code Playgroud)


nyb*_*bon 5

如果您使用的是 Java 8 或更高版本,这里是一个单语句解决方案,可以自己控制格式:

String properties = System.getProperties().entrySet()
            .stream()
            .map(e -> e.getKey() + ":" + e.getValue())
            .collect(Collectors.joining(", "));
Run Code Online (Sandbox Code Playgroud)