我放棄了將我的配置作爲簡單文本文件並使用完整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 + '}';
}
}
Person類
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()));
}
}
您是否嘗試過使用'java.util.Scanner'?否則,我不知道任何_straightforward_方式 –
我使用掃描儀一次獲取一行,然後String.split剪切碎片,比我不想查看數組的每個逗號分隔值,但做更聰明的事。我目前正在查看[Arrays.fill()](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#fill%28java.lang.Object [], %20int,%20int,%20java.lang.Object%29) – Agostino
'Arrays.fill'填充所有具有相同值的數組單元格,恐怕你必須'拆分'每個逗號分隔列表並將值轉換爲一 –