Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Please forgive this quesiton if it has already been answered, but I have been searching online for the past hour to try to figure it out.

I'm working on getting back into Java programming and I'm trying to understand the best way to save/read data I would be storing in my application. Would I put everything into a text file and read it all in when the application starts and save it all on exit? I figured that might eat up too much memory if the application was too large?

like image 428
sweaty Avatar asked Mar 26 '13 15:03

sweaty


2 Answers

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?

like image 85
Philipp Avatar answered Nov 14 '22 23:11

Philipp


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

  • Ex: http://www.mkyong.com/java/java-properties-file-examples/

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.

  • Ex: http://www.mkyong.com/tutorials/jdbc-tutorials/
like image 31
TheEwook Avatar answered Nov 14 '22 23:11

TheEwook