package com.mindprod.example;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.Enumeration;
import java.util.Properties;

/**
 * example use of java.util.Properties for non-system, user Properties.
 * <p/>
 * composed with IntelliJ IDEA
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.1 2008-07-30
 */
public final class TestProperties
    {
    // --------------------------- main() method ---------------------------

    /**
     * TEST harness
     *
     * @param args not used
     * @throws IOException Let Java report any problem.
     */
    public static void main( String[] args ) throws IOException
        {
        Properties props = new Properties();
        FileInputStream fis =
                new FileInputStream( "C:/temp/sample.properties" );
        props.load( fis );
        fis.close();
        // if the there is no such keyword, will will get null as a result.
        String logoPng = props.getProperty( "window.logo" );
        out.println( "window.logo" + "=[" + logoPng + "]" );

        // if there is no such keyword, will get the default "25"
        // Note numeric values appear as Strings, not int.
        // leading/trailing spaces have been automatically trimmed.
        int height = Integer.parseInt( props.getProperty( "height", "25" ) );
        out.println( "height" + "=[" + height + "]" );

        // changing a property and saving the properties
        props.setProperty( "window.logo", "resources/sunLogo.png" );

        // enumerate all the property keyword=value pairs
        Enumeration keys = props.keys();
        while ( keys.hasMoreElements() )
            {
            // need cast since Properties are non-generified Hashtables.
            String keyword = ( String ) keys.nextElement();
            String value = ( String ) props.get( keyword );
            out.println( keyword + "=[" + value + "]" );
            // prints in effectively random order.
            }

        FileOutputStream fos =
                new FileOutputStream( "C:/temp/updatedsample.properties" );
        // saving will lose your comments, lose blank lines, and scramble the
        // order.
        props.store( fos, "sample properties with comments lost" );
        fos.close();
        }
    }