I need to produce fixed length string to generate a character position based file. The missing characters must be filled with space character.
As an example, the field CITY has a fixed length of 15 characters. For the inputs “Chicago” and “Rio de Janeiro” the outputs are
" Chicago" " Rio de Janeiro"
.
Since Java 1.5 we can use the method java.lang.String.format(String, Object…) and use printf like format.
The format string
"%1$15s"do the job. Where1$indicates the argument index,sindicates that the argument is a String and15represents the minimal width of the String.Putting it all together:
"%1$15s".For a general method we have:
Maybe someone can suggest another format string to fill the empty spaces with an specific character?