Blog Reacción Estudio

¡Tu zona de aprendizaje!

Guardar todos los valores del archivo .properties en Java

Cuando trabajamos con un archivo de propiedades (.properties) en Java, suele ocurrir que cuando modificamos una propiedad y guardamos el valor en el archivo sólo guarda la última propiedad y las otras propiedades que teníamos se pierden.

Para solucionar esto hemos creado una clase en Java para que primero guarde en un Array todos las propiedades de este archivo «.properties«, para que cuando guardemos lo hagamos con todas las propiedades y no sólo la última.

La clase es la siguiente:

// @author - Reaccionestudio.com & Womp.es

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PropertiesHelper 
{
    private static String configFilePath = "config.properties";
    private static Properties configProp = new Properties();
    private static InputStream input = null;
    private static OutputStream output = null;
    
    /**
     * Gets cofig property from config.properties file.
     * @param propName (Property name)
     * @return String
     */
    public static String getConfProperty(String propName)
    {
        String ret = "";
        
        try 
        {
            input = new FileInputStream(configFilePath);
            
            // load config file
            configProp.load(input);
            
            // get property value
            ret = configProp.getProperty(propName);            
        } 
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        finally 
        {
            if (input != null) 
            {
                try 
                {
                    input.close();
                }
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
        }
        
        return ret;
    }
    
    /**
     * Sets cofig property from config.properties file.
     * @param propName (Property name)
     * @param propValue (Property value)
     * @return Boolean
     */
    public static Boolean setConfProperty(String propName, String propValue)
    {
        Boolean ret = false;
        
        int size = PropertiesHelper.getNumKeysConfigFile();
        String config[][] = new String[size][2];
        
        // Array with the config file data
        config = PropertiesHelper.getConfigFileValues();
        
        // Set the new value to the array
        for(int i=0; i < config.length; i++)
        {
            if(config[i][0].equals(propName))
            {
                config[i][1] = propValue;
                System.out.println(config[i][0] + " - " + config[i][1]);
            }
        }
        
        // Save the new .properties file.
        try 
        {
            output = new FileOutputStream(configFilePath);
            
            // sets value to property
            for(int i=0; i < config.length;i++)
            {
                configProp.setProperty(config[i][0], config[i][1]);
            }
            
            // save new changes on 'config.properties' file
            configProp.store(output, null);
        
            ret = true;
        } 
        catch (IOException io) 
        {
            io.printStackTrace();
        }
        finally 
        {
            if (output != null) 
            {
                try 
                {
                    output.close();
                } catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }
    
    /**
     * Gets the number of keys in the properties file.
     * @return int
     */
    private static int getNumKeysConfigFile()
    {
        int ret = 0;
        
        try
        {
            InputStream is = new FileInputStream(configFilePath);
            configProp.load(is);
            
            ret = configProp.size();
        }
        catch (FileNotFoundException ex) 
        {
            Logger.getLogger(PropertiesHelper.class.getName()).log(Level.SEVERE, null, ex);
        } 
        catch (IOException ex) 
        {
            Logger.getLogger(PropertiesHelper.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return ret;
    }
    
    /**
     * Returns an array with the keys and values from the properties file.
     * @return array[][]
     */
    public static String[][] getConfigFileValues()
    {
        int con = 0;
        int size = PropertiesHelper.getNumKeysConfigFile();                
        
        String ret[][] = new String[size][2];
        
        for (Enumeration e = configProp.keys(); e.hasMoreElements();)
        {
            Object obj = e.nextElement();
            
            ret[con][0] = obj.toString();
            ret[con][1] = configProp.getProperty(obj.toString());
            con++;
        }
        
        return ret;
    }
    
    /**
     * Prints in console the content of the properties file.
     */
    public static void printPropertiesFile()
    {
        int size = PropertiesHelper.getNumKeysConfigFile();                
        String ret[][] = new String[size][2];
        
        ret = PropertiesHelper.getConfigFileValues();
        
        System.out.println("Properties file:\n");
        for(int i = 0; i < ret.length; i++)
        {
            System.out.println("[" + i + "] " + ret[i][0] + " => " + ret[i][1]);
        }
        System.out.print("\n");
    }
    
}

Vamos con un ejemplo, imaginemos que nuestro archivo «config.properties» tiene el siguiente contenido:

nombre=Alberto
blog=reacción estudio
oficio=programador

Por ejemplo para modificar la propiedad «blog«, utilizaremos el método «setConfProperty» de la clase:

PropertiesHelper.setConfProperty("blog", "Nuevo valor para la propiedad blog.");

Y veremos que nuestro archivo «config.properties» queda así:

nombre=Alberto
blog=Nuevo valor para la propiedad blog.
oficio=programador

También podemos imprimir el contenido de nuestro archivo «properties» por pantalla:

PropertiesHelper.printPropertiesFile();