我放弃了将配置制作为简单文本文件的想法,转而使用完整的 XML。
我找到了一个不错的库,XStream,它可以生成一些冗长但可读性很强的文件。
示例输出和代码
<Person>
<firstname>Joe</firstname>
<lastname>Walnes</lastname>
<phone>
<code>123</code>
<number>1234-456</number>
</phone>
<fax>
<code>123</code>
<number>9999-999</number>
</fax>
</Person>
电话号码类
public class PhoneNumber {
private int code;
private String number;
public PhoneNumber(int code, String number) {
this.code = code;
this.number = number;
}
@Override
public String toString() {
return "PhoneNumber{" + "code=" + code + ", number=" + number + '}';
}
}
人物类
public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public void setPhone(PhoneNumber phone) {
this.phone = phone;
}
public void setFax(PhoneNumber fax) {
this.fax = fax;
}
@Override
public String toString() {
return "Person{" + "firstname=" + firstname + ", lastname=" + lastname + ", phone=" + phone + ", fax=" + fax + '}';
}
}
跑步者类
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Runner {
private static final Logger LOG = Logger.getLogger(Runner.class.getName());
public static void main(String[] args) {
XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
// shorten tag names when saved
xstream.alias(Person.class.getSimpleName(), Person.class);
xstream.alias(PhoneNumber.class.getSimpleName(), PhoneNumber.class);
// create object
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
// serialize
String xml = xstream.toXML(joe);
// open file
File configFile = new File("Config.txt");
// write to file
try (PrintWriter writer = new PrintWriter(configFile, "UTF-8");) {
xml = xstream.toXML(joe);
writer.println(xml);
} catch (FileNotFoundException | UnsupportedEncodingException ex) {
LOG.log(Level.SEVERE, null, ex);
}
// read file
try (Scanner scanner = new Scanner(configFile, "UTF-8");) {
scanner.useDelimiter("\\A");
xml = scanner.next();
} catch (FileNotFoundException ex) {
LOG.log(Level.SEVERE, null, ex);
}
// deserialize
Person newJoe = (Person) xstream.fromXML(xml);
System.out.println("Does toString return the same String? " + joe.toString().equals(newJoe.toString()));
}
}