Java: saving variables in a file

I know how to write text to a file and store it in Java, but I was wondering if there is a way to store a large number of variables that can be extracted from the file at a later date and return them back to Java as variables.

I would keep numbers and strings, but their groups.

Thanks:)

+7
source share
3 answers

Java can read property files, such as reading a map. This gives you an easy way to store information using a key / value system.

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

+13
source

Use XML! You will transfer variables. Even your coffee maker can use them.

A SAX parser is built in Java.

Here is the 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"); 
+5
source

It is best to do this to create an XML file. It can store any object in any collection.

I think XML is the best way to save it and get it later.

0
source

All Articles