Properties

La clase Properties nos ayuda a manejar preferencias de los usuarios y otras puntos más que se requieran como datos de configuración del sistema.
Utilizando un atributo seguido por un signo igual se coloca la información que queremos persistir.
Haremos un ejemplo donde creamos un archivo de nombre "datos.properties", dentro de este archivo le agregamos un atributo de nombre blog y el contenido será http://ampliandoconocimientosjava.blogspot.com/.
El archivo debe quedar así
blog=http://ampliandoconocimientosjava.blogspot.com/

Lo guardamos y probamos este código

public class ObtenerPropiedades {

    public static String getPropiedades(String archivoIn, String nombrePropiedad)
            throws FileNotFoundException, IOException, PropertyException {

        Properties prop;
        InputStream in;
        String propiedad = "";

        in = ObtenerPropiedades.obtenerArchivo(archivoIn);

        prop = new Properties();

        prop.load(in);
        if (!nombrePropiedad.trim().equals("")) {
            propiedad = prop.getProperty(nombrePropiedad);
            if (propiedad == null) {
                throw new PropertyException("Propiedad \"" + nombrePropiedad + "\" no fue encontrada.");
            }
        }else{
            throw new PropertyException("Falta el nombre de la propiedad.");
        }


        return propiedad;
    }

    public static InputStream obtenerArchivo(String archivoIn) throws FileNotFoundException {
        InputStream in = new FileInputStream(archivoIn);
        return in;
    }
}

public class DatosProperties {

    public static void main(String arg[]) {
        try {
            String strBlog;
            strBlog = ObtenerPropiedades.getPropiedades("/home/arielb/datos.properties", "blog");
            System.out.println("Valor: " + strBlog);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DatosProperties.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DatosProperties.class.getName()).log(Level.SEVERE, null, ex);
        } catch (PropertyException ex) {
            System.err.println(ex);
            //Logger.getLogger(DatosProperties.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

public class PropertyException extends Exception {

    public PropertyException(String mensaje) {
        super(mensaje);
    }

    public PropertyException() {
        super();
    }

    public PropertyException(String mensaje, Throwable causa) {
        super(mensaje, causa);
    }

    public PropertyException(Throwable mensaje) {
        super(mensaje);
    }
}

resultado:

Dirección del blog: http://ampliandoconocimientosjava.blogspot.com/

No hay comentarios: