2009-10-16 58 views
10

我有一个Java Properties对象,我从一个内存String,之前加载到内存从实际.properties文件中像这样加载:的Java Properties对象的字符串

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

的UTIL fileToString实际上读在文件中的文本中,其余代码将其存储在名为propertyFilesCacheHashMap中。后来,我读从HashMap文件文本作为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); 

在这一点上,我把它换成我的财产在我的记忆性文件和我想要从Properties对象中获取文本,就好像我正在读取像上面所做的File对象一样。有没有一种简单的方法来做到这一点,或者我将不得不迭代属性并手动创建String

回答

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

这并获得成功,谢谢! – 2009-10-16 17:34:01

+4

值得注意的是,这不会让你直接渲染属性,也就是说你不能直接将该字符串弹出到文件中,并将其作为属性文件加载回来。这是因为** Properties.list()方法**预先考虑一个头添加到列表: ' - 上市性能--' 更有可能的是你想使用的** Properties.store()* *以下评论@joev评论中描述的方法。 – 2012-07-17 18:41:19

2

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

公共无效店(OutputStream中出来, 字符串评论) 抛出IOException异常

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

6

它不直接关系到你的问题,但如果你只是想打印出来的属性进行调试,你可以做这样的事情

properties.list(System.out); 
9

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

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

您使用该方法获得带时间戳的标题。 – selle 2014-04-09 06:43:53

0

另一个功能打印领域的所有值是:

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