Java 属性对象到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1579113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:26:13  来源:igfitidea点击:

Java Properties object to String

javastringproperties

提问by Casey Crites

I have a Java Propertiesobject that I load from an in-memory String, that was previously loaded into memory from the actual .propertiesfile like this:

我有一个Properties从 in-memory 加载的 Java对象,该对象String以前从实际.properties文件加载到内存中,如下所示:

this.propertyFilesCache.put(file, FileUtils.fileToString(propFile));

The util fileToStringactually reads in the text from the file and the rest of the code stores it in a HashMapcalled propertyFilesCache. Later, I read the file text from the HashMapas a Stringand reload it into a Java Propertiesobject like so:

utilfileToString实际上从文件中读取文本,其余代码将其存储在一个HashMap被调用的propertyFilesCache. 后来,我从HashMapas a读取文件文本String并将其重新加载到 JavaProperties对象中,如下所示:

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);

At this point, I've replaced my property in my in-memory property file and I want to get the text from the Propertiesobject as if I was reading a Fileobject like I did up above. Is there a simple way to do this or am I going to have to iterate over the properties and create the Stringmanually?

在这一点上,我已经替换了我的内存属性文件中的属性,并且我想从Properties对象中获取文本,就像我正在读取一个File对象一样,就像我上面所做的那样。有没有一种简单的方法可以做到这一点,还是我必须遍历属性并String手动创建?

采纳答案by lsiu

public static String getPropertyAsString(Properties prop) {    
  StringWriter writer = new StringWriter();
  prop.list(new PrintWriter(writer));
  return writer.getBuffer().toString();
}

回答by joev

I don't completely understand what you're trying to do, but you can use the Properties class' store(OutputStream out, String comments) method. From the javadoc:

我不完全理解您要做什么,但您可以使用 Properties 类的 store(OutputStream out, String comments) 方法。从javadoc

public void store(OutputStream out, String comments) throws IOException

Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method.

public void store(OutputStream out, String comments) 抛出 IOException

将此 Properties 表中的此属性列表(键和元素对)以适合使用 load(InputStream) 方法加载到 Properties 表的格式写入输出流。

回答by maestr0

It's not directly related to your question but if you just want to print out properties for debugging you can do something like this

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

properties.list(System.out);

回答by Banana

There seems to be a problem with @Isiu answer. After that code Properties are truncated, like there is some limit to string length. Proper way is to use code like this:

@Isiu 的回答似乎有问题。在该代码属性被截断之后,就像字符串长度有一些限制一样。正确的方法是使用这样的代码:

public static String getPropertyAsString(Properties prop) { 
    StringWriter writer = new StringWriter();
    try {
        prop.store(writer, "");
    } catch (IOException e) {
        ...
    }
    return writer.getBuffer().toString();
}

回答by Moebius

Another function to print all the values of a field is :

打印一个字段的所有值的另一个函数是:

public static <T>void   printFieldValue(T obj)
{
    System.out.printf("###" + obj.getClass().getName() + "###");
    for (java.lang.reflect.Field field : obj.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        String name = field.getName();
        Object value = null;
        try{
            value = field.get(obj);
        }catch(Throwable e){}
        System.out.printf("#Field name: %s\t=> %s%n", name, value);
    }
}

回答by GMsoF

You can do as below also:

您也可以执行以下操作:

Properties p = System.getProperties();
Enumeration keys = p.keys();
while (keys.hasMoreElements()) {
    String key = (String)keys.nextElement();
    String value = (String)p.get(key);
    System.out.println(key + ": " + value);
}

回答by nybon

If you are using Java 8 or above, here is a single statement solution with the possibility to control the format by yourself:

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

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