[英]How to add List into properties file?
I am converting properties file into xml format like below . 我正在将属性文件转换为xml格式,如下所示。
public class XmlPropertiesWriter {
public static void main(String args[]) throws FileNotFoundException, IOException {
//Reading properties files in Java example
Properties props = new Properties();
FileOutputStream fos = new FileOutputStream("C:\\Users\\Desktop\\myxml.xml");
props.setProperty("key1", "test");
props.setProperty("key2", "test1");
//writing properites into properties file from Java
props.storeToXML(fos, "Properties file in xml format generated from Java program");
fos.close();
}
}
This is working fine.But I want to add one ArrayList into this xml file,How can I do this,Any one help me. 这工作正常。但是我想向这个xml文件中添加一个ArrayList,我该怎么做,任何人都可以帮助我。
You can (un)serialized the list into string representation to store the data into the properties file: 您可以将列表序列化为字符串表示形式,以将数据存储到属性文件中:
ArrayList<String> list = new ArrayList<>( );
String serialized = list.stream( ).collect( Collectors.joining( "," ) );
String input = "data,data"
List<String> unserialized = Arrays.asList( input.split( "," ) );
With this method, take care to use a seperator which is never contained in your data. 使用此方法时,请小心使用数据中永远不会包含的分隔符。
Otherwise, write a xml (or json) file reader/writer to do what you want with support of list element 否则,编写一个xml(或json)文件读取器/写入器,以支持list元素来完成所需的操作
Depends on what type the ArrayList is. 取决于ArrayList的类型。 If it's a String type you can do 如果是字符串类型,则可以执行
arrayList.toArray(new String[arrayList.size()]);
If the type is an object you can create a StringBuilder and add all the values seperated by a ; 如果类型是一个对象,则可以创建一个StringBuilder并添加所有用a分隔的值; or : so you can split when needed 或:因此您可以在需要时拆分
final StringBuilder builder = new Stringbuilder();
final List<Point> list = new ArrayList<Point>();
list.add(new Point(0, 0));
list.add(new Point(1, 0));
for(final Point p : list) {
builder.append(p.toString()).append(";");
}
properties.setProperty("list", builder.toString());
When you load the properties you can simply do then 加载属性时,您只需执行以下操作
final List<Point> list = new ArrayList<Point>();
final String[] points = properties.getProperty("list").split(";");
for(final String p : points) {
final int x = Integer.parseInt(p.substring(0, p.indexOf(","));
final int y = Integer.parseInt(p.substring(p.indexOf(","), p.indexOf(")"));
list.add(new Point(x, y);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.