Domanda

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 !

È stato utile?

Soluzione

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.

Altri suggerimenti

If you are sure the particular string {somethinig} is not being used in your string (as it seems to be the case) why not just keep the string as is and use String.replace to change it to whatever values you have later?

Can this help?

Placeholders that should be replaced on second stage are quoted initially.

public static void main(String[] args) {
    final String partialResult = MessageFormat.format("{0} '{0}' '{1}' {1}", "zero", "three");
    System.out.println(partialResult);
    final String finalResult = MessageFormat.format(partialResult, "one", "two");
    System.out.println(finalResult);
}

Then your format string becomes:

{0}/suhdp run -command "suhilb" -input /sufiles/'{0}' -output /seismicdata/mr_files/'{1}'/ -cwproot {1}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top