View Full Version : [JAVA] File di configurazione di una applicazione
Salve,
esiste qualcosa del genere simile alle applicazione .NET:
un file (tipicamente xml) con coppie variabli-valore, che è possibile leggere attraverso un oggetto "ConfigurationSettings".
Ho la necessità di memorizzare dati per connetere ad un db, ma non voglio "hardcodarli" deentro un oggetto, anche perchè se poi cambiano devo ricompilare.
help?
incredibile! ogni volta questa classe mi torna di aiuto:
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
/**
* This class provide a generic method to handle a configuration file using XML
*/
public class Configuration {
private String filename = null;
/**
* This is the constructor
* @param filename The configuration file
*/
public Configuration(String filename) {
super();
this.filename = filename;
}
/**
* Get a specified value from the configuration file
* @param name The name of the property
* @return The value of the property
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
*/
public String getValue(String name) throws SAXException, IOException, ParserConfigurationException {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(this.filename);
Element root = doc.getDocumentElement();
NodeList children = root.getChildNodes();
for(int i = 0; i < children.getLength(); i++) {
Node item = children.item(i);
if(item instanceof Element && item.getNodeName().equalsIgnoreCase(name)) {
NodeList children1 = item.getChildNodes();
for (int j = 0; j < children1.getLength(); j++) {
Node item1 = children1.item(j);
if(item1 instanceof Text && !item1.getNodeValue().trim().equals("")) {
return item1.getNodeValue().trim();
}
}
}
}
return null;
}
/**
* Set a value in the configuration file
* @param name The name of the property
* @param value The value of the property
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
* @throws TransformerException
*/
public void setValue(String name, String value) throws SAXException, IOException, ParserConfigurationException, TransformerException {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(this.filename);
Element root = doc.getDocumentElement();
NodeList children = root.getChildNodes();
for(int i = 0; i < children.getLength(); i++) {
Node item = children.item(i);
if(item instanceof Element && item.getNodeName().equalsIgnoreCase(name)) {
NodeList children1 = item.getChildNodes();
for (int j = 0; j < children1.getLength(); j++) {
Node item1 = children1.item(j);
if(item1 instanceof Text && !item1.getNodeValue().trim().equals("")) {
item1.setNodeValue(value);
}
}
}
}
doc.normalize();
DOMSource dom=new DOMSource(doc);
TransformerFactory tFactory =TransformerFactory.newInstance();
Transformer transformer = null;
transformer = tFactory.newTransformer();
StreamResult result = new StreamResult(filename);
transformer.transform(dom, result);
}
}
semplice, essenziale.. spero che è quello che cerchi :D
ciao
Salve,
esiste qualcosa del genere simile alle applicazione .NET:
un file (tipicamente xml) con coppie variabli-valore, che è possibile leggere attraverso un oggetto "ConfigurationSettings".
Ho la necessità di memorizzare dati per connetere ad un db, ma non voglio "hardcodarli" deentro un oggetto, anche perchè se poi cambiano devo ricompilare.
help?
Puoi utilizzare la classe java.util.Properties, che ti consente di specificare un semplice file di testo cosi composto :
chiave1 = valore1
chiave2 = valore2
il file dovra chiamarsi miofile.properties, e verra' caricato nel seguente modo :
FileInputStream fis =
new FileInputStream( "C:/miofile.properties" );
Properties properties = new Properties();
properties.load(fis);
Ogni volta che avrai bisogno di un valore, bastera chiamare il metodo getProperty
String valore1 = props.getProperty( "chiave1" );
Puoi utilizzare la classe java.util.Properties, che ti consente di specificare un semplice file di testo cosi composto :
chiave1 = valore1
chiave2 = valore2
il file dovra chiamarsi miofile.properties, e verra' caricato nel seguente modo :
FileInputStream fis =
new FileInputStream( "C:/miofile.properties" );
Properties properties = new Properties();
properties.load(fis);
Ogni volta che avrai bisogno di un valore, bastera chiamare il metodo getProperty
String valore1 = props.getProperty( "chiave1" );
:doh: non ci avevo mai pensato
entrambi gentilissimi e veloci :) grazie
preferisco la versione "nativa" di Jo3, provo subito!
entrambi gentilissimi e veloci :) grazie
preferisco la versione "nativa" di Jo3, provo subito!
Se vuoi usare l'XML, properties ha due metodi ad hoc, storeToXML e loadFromXML, funzionano come il load "normale" solo che salvano/leggono in un formato basato su XML.
C'è poi (Java 6) il package java.util.prefs che contiene gli strumenti utili a creare e gestire una sorta di registro di sistema o utente.
Usa XML, maneggia oggetti Preferences, è ramificabile, nel senso che hai 'sto documento unico che poi puoi suddividere. Ad esempio crei un nodo con il nome del produttore del software, dentro ci infili un nodo con il nome del software e là dentro ci sbatti le impostazioni del programma.
Guarda le classi PreferencesFactory (che ha due metodi) e Preferences (che ne ha un bel po' in più ma gli indispensabili sono i put, i get, remove e create).
vBulletin® v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.