Humphrey
Humphrey

Reputation: 579

Java: Store variables in file

I know how to write text to a file and store it in Java, but I was wondering if there is a way of storing lots of variables that can be retrieved from the file at a later date, and put back into the Java application as variables.

I would be storing numbers and strings, but groups of them.

Thanks :)

Upvotes: 9

Views: 18126

Answers (3)

Costis Aivalis
Costis Aivalis

Reputation: 13728

Use XML! You will make your variables portable. Even your coffee machine will be able to use them.

A SAX parser is built in Java.

Here is a Java snippet for writing an XML file:

public void saveToXML(String xml) {
    Document dom;
    Element e = null;
    // get an instance of factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        // using a factory get an instance of document builder
        DocumentBuilder db = dbf.newDocumentBuilder();
        // create an instance of DOM
        dom = db.newDocument();
        // create the root element
        Element rootElement = dom.createElement("myparameters");
        // create data elements and place them under root
        e = dom.createElement("brightness");
        e.appendChild(dom.createTextNode(brightness));
        rootElement.appendChild(e);

Here is a Java snippet for reading an XML file:

public boolean loadFromXML(String xml) {    
    Document dom;
    // get an instance of the factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        // using factory get an instance of the document builder
        DocumentBuilder db = dbf.newDocumentBuilder();
        // parse using builder to get DOM representation of the XML file
        dom = db.parse(xml);
        Element doc = dom.getDocumentElement();
        // get the data 
        brightness = getTextValue(brightness, doc, "brightness");
        contrast = getTextValue(contrast, doc, "contrast");

Upvotes: 5

Talha Ahmed Khan
Talha Ahmed Khan

Reputation: 15483

Wel the best way to do this is to make an XML file. It can store any object in any sort of collection.

I guess the XML is the best way to keep it and retrieve it later on.

Upvotes: 0

user623990
user623990

Reputation:

Java can read properties files like it reads a map. This gives you an easy way of storing information using a key/value system.

Check out http://download.oracle.com/javase/6/docs/api/java/util/Properties.html

Upvotes: 14

Related Questions