开发者

Best means to store/add/delete a simple set of data in Java

I'm looking to have certain data stored for more than the lifetime of the program. Basically it's going to be an ID number, and two other elements that follow each ID. There would less than 20 entries at all times, so the means of storing it/retrieving it would not have to be restrained by capacity/size issues.

I thought about XML but it seems to be a little more work than necessary for this small of a procedure. I also 开发者_运维技巧thought about just keeping the entries in a text file... I suppose the biggest issue would be what means to search for an item and delete an item.

I'm sure someone with more experience would have a better idea for what I should do. Any suggestions would be much appreciated.


As you mentioned the data remains static so it can be considered as a config type data. I recommend using a properties file approach here using the Properties class.

You can check out the tutorials on how to utilize it here and also another one here.

For your scenario, the key would be the id number and the values would be the 2 elements that corresponds to that id number.

Example of myApp.props file:

id=values
1=a,b
2=c,d

Then you can retrieve the values this way:-

        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("myApp.props"));
            if(properties.containsKey("1")){
                String[] propertyValues = properties.getProperty("1").split(","); //gets you a and b
            }
        } catch (IOException e) {
            //handle it
        } finally{
            //handle it
        } 


If you are not interested in making the data store readable by a human, consider making your object serializable and simply serializing it into a file output stream.

You can even serialize lists of serialized objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜