Java Programming - Best way to save/read data for an application [closed]

心不动则不痛 提交于 2019-12-01 05:36:21

I would say if you need to store few information you can use a properties file.

If you need to store more complex structure than just properties I suggest using a database (HSQL, Oracle, Mysql, MSSQL, etc...). Depending of you needs.

It depends on how much data you have.

When you want to store a handfull of key/value pairs like some user preferences, you could use the Preferences class, which is implemented using the registry on Windows, config files on Linux and whatever else is the preferred way to store user preferences on other plattforms.

When you have actual data which is too much for the registry but not enough to warrant a database (something in the order of a few MB), using one or more flat files might be a solution. When the data is complex, it might be a good idea to use a standardized format like XML instead of something homebrewed. Java has classes which allow easy parsing and serialization of XML. An alternative quick&dirty solution would be to use ObjectStreams to save and restore whole objects. This is very easy to implement, but might not be very efficient because it stores a lot of meta-information which is likely unnecessary.

But when you have a lot of data (more than you are comfortable to read and write completely), it might be a smart move to use a database. A database allows you easy access to huge amounts of data (in the orders of several GB) and offers you a lot of features for free which would be hard to implement yourself (like searching for records using indices). Databases aren't magic. They also use files to store their data (files with very clever structure, however). You could replicate every feature of a database yourself. But why should you reinvent the wheel when you can just use an existing solution?

If the question is also how to get the data into and out of the file, I just wanted to throw out the keyword "serialization", in case you're not familiar with it. Google it, there's tons of tutorials. In a nutshell, Java has built in support for writing objects to and reading objects from binary bytestreams, which you can then of course write to / read from files. So you won't have to implement the code for storing and reading your different members. Just identify the objects in your code that hold program state and serialize those. You can also serialize to XML making the created files manually editable.

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