Lector genérico de fichero .properties en JAVA


Hoy vengo a compartir un pequeño código en JAVA el cual permite la lectura de cualquier fichero .properties en JAVA. Este código implementa una sencilla clase que se inicializa con el fichero y retorna la clave dada.
Hola a todos,



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


public class PropertiesReader {
    String result = "";
    InputStream inputStream;
    String propFileName = "";
    public PropertiesReader(String propFileName){
     this.propFileName = propFileName;
    }

 public String getPropValues(String propertie) throws IOException {
        try {
            Properties prop = new Properties();
            inputStream = new FileInputStream(new File(
                          PropertiesReader.class.getProtectionDomain().getCodeSource().
                         getLocation().getPath().replace("%20", " ")+ this.propFileName));
            if (inputStream != null) {
                prop.load(inputStream);
            } else {
                throw new FileNotFoundException("Archivo properties '" + propFileName + "' no disponible");
            } 
            result = prop.getProperty(propertie);
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        } finally {
            inputStream.close();
        }
        return result;
    }
}
Para el llamado desde cualquier clase utilizaremos el siiguiente codigo

public final static String propFileNameDB = "database.properties";
PropertiesReader readerDB = new PropertiesReader(propFileNameDB);

Comentarios

Entradas populares de este blog

Un dia como hoy...

El Tao de la programación