我无法想象在我创建的xml数据库中更改我的值。
我首先使用XMLEncoder从我的Person类
创建我的Database.xml Person Peter = new Person("Peter", 22);
FileOutputStream fos = new FileOutputStream(new File("Database.xml"));
XMLEncoder encoder = new XMLEncoder(fos);
encoder.writeObject(Peter);
encoder.close();
fos.close();
现在我可以像
那样解码它 FileInputStream fis = new FileInputStream(new File("Database.xml"));
XMLDecoder decoder = new XMLDecoder(fis);
Person Peter = (Person) decoder.readObject();
decoder.close();
fis.close();
现在我很容易就像
一样 Peter.getName();
现在我的问题出现了。
让我们在我的程序中说,在某些时候名称会改变,例如:
Peter.setName("Christian");
现在,如何将这些新信息保存到我的xml-database?
答案 0 :(得分:0)
首先,这只是您的任务的可能解决方案。我很确定还有很多其他方法可以做到这一点。
对于代码感到抱歉,我知道它并不完美,但我几乎没有时间做这件事。
Person.java 类(我们将要保存到数据库中):
public class Person implements Serializable {
private int id;
private String firstName;
private String lastName;
private int age;
public Person() {
}
public Person(int id, String firstName, String lastName, int age) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// getters and setters are required (I skipped here just to make it shorter)
// I also have toString() method in my code to get person object nicely outputted
// where I need it.
public String toString() {
return "Person{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", age=" + age +
'}';
}
}
主要代码:
public class Test {
public static void main(String[] args) {
// here I have a few objects (test data)
final Person person1 = new Person(1, "Foo", "Bar", 15);
final Person person2 = new Person(2, "Aaa", "Bbb", 35);
// I want to store them in a list to save the whole list
final List<Person> persons = new ArrayList<>();
persons.add(person1);
persons.add(person2);
// save 2 persons to DB (the method itself is below)
Test.saveToDB(persons);
// read from DB and just print to the console
List<Person> dataFromDB = Test.readFromDB();
System.out.println("\nData from database:");
dataFromDB.forEach(System.out::println);
// not let's imagine we need to update Foo user
// we need to find it first, I know that this user has ID = 1
// we could use firstName or lastName as a search criteria
// but I assume those are not unique
Optional<Person> fooBar = dataFromDB.stream().filter(person -> person.getId() == 1).findFirst();
if (fooBar.isPresent()) {
fooBar.get().setAge(25); // update
fooBar.get().setFirstName("New Name"); // update
}
System.out.println("\nData after update:");
dataFromDB.forEach(System.out::println);
// now we can save UPDATED data to the DB
Test.saveToDB(dataFromDB);
// after this line the XML file contains updated data !
// just open the file and check
}
// basically as in your example - this method just saves to the file
// using XMLEncoder
public static void saveToDB(final List<Person> persons) {
try (XMLEncoder xmlEncoder = new XMLEncoder(new BufferedOutputStream(
new FileOutputStream("Database.xml")))) {
// save data to database
xmlEncoder.writeObject(persons);
System.out.println("\nData saved successfully.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
// the same API but for reading data from XML file
public static List<Person> readFromDB() {
final FileInputStream fis;
try {
fis = new FileInputStream(new File("Database.xml"));
final XMLDecoder decoder = new XMLDecoder(fis);
final List<Person> persons = (List<Person>) decoder.readObject();
return persons;
} catch (FileNotFoundException e) {
e.printStackTrace();
return Collections.emptyList();
}
}
}
希望这有一定道理。
快乐编码:)