Best way to save data in a Java application?

白昼怎懂夜的黑 提交于 2021-02-04 15:00:12

问题


I'm trying to find the best way to save the state of a simple application. From a DB point-of-view there are 4/5 tables with date fields and relationships off course.

Because the app is simple, and I want the user to have the option of moving the data around (usb pen, dropbox, etc), I wanted to put all data in a single file.

What is the best way/lib to do this?

XML usually is the best format for this (readability & openness), but I haven't found any great lib for this without doing SAX/DOM.


回答1:


If you want to use XML, take a look at XStream for simple serialization of Java objects into XML. Here is "Two minute tutorial".

If you want something simple, standard Java Properties format can be also a way to store/load some small data.




回答2:


consider using plain JAXB annotations that come with the JDK:

@XmlRootElement  
private class Foo {  
    @XmlAttribute  
    private String text = "bar";
}

here's a blog-post of mine that gives more details on this simple usage of JAXB (it also mentiones a more "classy" JAXB-based approach -- in case you need better control over your XML schema, e.g. to guarantee backwards compatibility)




回答3:


2 other options you might consider -

  • Hsqldb is a small sql db written in java. More relevant for your purposes, it can be configured to simply write to a csv file as it's data store, so you could conceivably use it's text output as a portable datastore and still use sql, if that's what you prefer.
  • A second option might be to write the datastore directly to a serialized file either directly or through a library like prevayler. Very good performance and simple to implement, cons are the fragility and opacity of the format.

But if the data is small enough, xml is probably much less bother.




回答4:


If you don't need to provide semantic meaning to your data then XML is probably a wrong choice. I would recommend using the fat-free alternative JSON, which is much more naturally built for data structures.



来源:https://stackoverflow.com/questions/513343/best-way-to-save-data-in-a-java-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!