views:

723

answers:

2

Hello honorable forum,

I'm building a ResourceBundle from a file, this bundle holds < String, String> values.

InputStream in = getClass().getResourceAsStream("SQL.properties");
properties = new PropertyResourceBundle(in);
in.close();

I would like to add/replace on this bundle some properties that I'm passing from the command line using -Dsome.option.val.NAME1=HiEarth

I don't care dumping the old bundle and creating a new one instead.

Could you please tip?

I think that what I need to do is :

  1. Create from the bundle a HashMap< String, String>
  2. Replace values.
  3. Transform the HashMap into a InputStream. //This is the complicated part...
  4. Build the new bundle from that.
A: 

This might not be the best way to do it but it's the best I can think of: implement a subclass of ResourceBundle that stores the properties you want to add/replace, then set the parent of that bundle to be the PropertyResourceBundle you load from the input stream.

InputStream in = getClass().getResourceAsStream("SQL.properties");
properties = new PropertyResourceBundle(in);
in.close();
MyCLIResourceBundle b = new MyCLIResourceBundle(properties);
// use b as your bundle

where the implementation would be something like

public class MyCLIResourceBundle extends ResourceBundle {
    public MyCLIResourceBundle(ResourceBundle parent) {
        super();
        this.setParent(parent);
        // go on and load your chosen properties from System.getProperties() or wherever
    }
}
David Zaslavsky
A: 

This does some of what you want (converts the System.properties to a ResourceBundle). Better error handling is left up to you :-)

    
    public static ResourceBundle createBundle()
    {
        final ResourceBundle  bundle;
        final Properties      properties;
        final CharArrayWriter charWriter;
        final PrintWriter     printWriter;
        final CharArrayReader charReader;

        charWriter = new CharArrayWriter();
        printWriter = new PrintWriter(charWriter);

        properties = System.getProperties();
        properties.list(printWriter);

        charReader = new CharArrayReader(charWriter.toCharArray());

        try
        {
            bundle = new PropertyResourceBundle(charReader);

            return (bundle);
        }
        catch(final IOException ex)
        {
            // cannot happen
            ex.printStackTrace();
        }

        throw new Error();
    }
TofuBeer