简体   繁体   English

用Java XMLDecoder XMLEncoder写入XML数据库

[英]Write to XML-database in java XMLDecoder XMLEncoder

I cannot figure out to change my value in my created xml-database. 我不知道要更改我创建的xml数据库中的值。

I am first using XMLEncoder to create my Database.xml from my Person class 我首先使用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(); 

Now I can decode it like 现在我可以像解码

        FileInputStream fis = new FileInputStream(new File("Database.xml"));
        XMLDecoder decoder = new XMLDecoder(fis);

        Person Peter = (Person) decoder.readObject();

        decoder.close();
        fis.close();

And now it is easy for me to get like 现在我很容易得到

  Peter.getName();

Now comes my question. 现在是我的问题。

Lets say in my program, at some point the name changes, like: 可以说在我的程序中,名称有时会更改,例如:

 Peter.setName("Christian");

Now, how do I save this new information to my xml-database? 现在,如何将这些新信息保存到我的xml数据库中?

First of all, this is just a possible solution for your task. 首先,这只是您的任务的可能解决方案。 I am pretty sure there are many other ways to do that. 我很确定还有很多其他方法可以做到这一点。

And sorry for the code, I know it is not perfect, but I had almost no time for this. 对代码感到抱歉,我知道它并不完美,但是我几乎没有时间这样做。

Person.java class (that's what we are going to save into DB): 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 +
            '}';
    }
}

The main code: 主要代码:

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

Hope this makes some sense. 希望这有道理。

Happy Coding :) 快乐编码:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM