Search code examples
javamessageformat

Java MessageFormat - replace value at an index


I'm having a String like this :

{0}/suhdp run -command "suhilb" -input /sufiles/{1} -output /seismicdata/mr_files/{2}/ -cwproot {3}

The values at the 0th and the 3rd index need to replaced first. Later on, the 1st and 2nd indexes will replaced (on the already partially formatted String) and finally used.

I played around a bit with ChoiceFormat but was not able to pipe it with the MessageFormat class to achieve what I want to.

Any pointers are welcome !


Solution

  • Since you don't fill all values at once, I'd suggest you use a builder:

    public class MessageBuilder
    {
        private final String fmt;
        private final Object[] args;
    
        public MessageBuilder(final String fmt, final int nrArgs)
        {
            this.fmt = fmt;
            args = new Object[nrArgs];
        }
    
        public MessageBuilder addArgument(final Object arg, final int index)
        {
            if (index < 0 || index >= args.length)
                throw new IllegalArgumentException("illegal index " + index);
            args[index] = arg;
            return this;
        }
    
        public String build()
        {
            return MessageFormat.format(fmt, args);
        }
    }
    

    This way you can do:

    final MessageBuilder msgBuilder = new MessageBuilder("{0}/suhdp run -command \"suhilb\" -input /sufiles/{1} -output /seismicdata/mr_files/{2}/ -cwproot {3}", 4)
        .addArgument(arg0, 0).addArgument(arg3, 3);
    
    // later on:
    msgBuilder.addArgument(arg1, 1).addArgument(arg2, 2);
    // print result
    System.out.println(msgBuilder.build());
    

    This code probably lacks some error checking etc, and it is far from being optimal, but you get the idea.