Search code examples
javatext-formatting

Add exact number of spaces to start of string using java.util.Formatter


I am using Formatter to output Java code to a file. I want to add a specific number of spaces to the start of each line. My problem is I cannot find a way to do this "neatly". The standard options seem to only allow adding a minimum number of spaces but not a specific number of spaces.

As a work around, I am currently doing the following: out.format("%7s%s", "", "My text"); but I'd like to do it with only two arguments like this out.format("%7s", "My text");.

Does anyone know if there is a way to do this using the standard Formatter options?


Solution

  • I'm not exactly sure what you want here:

    out.format("xxx%10sxxx", "My text");
    // prints: xxx   My textxxx
    

    While:

    out.format("xxx%-10sxxx", "My text");
    // prints: xxxMy text   xxx
    

    As far as I know, there is no way to do the old C-style formatting to specify the size in an argument like "%*s" because then you could pass in (str.length() + 7).

    I'm afraid that your way seems to the the most "neat". If you can explain why you don't like it maybe we can find a better workaround.