Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Formatting output of a string

 
Mike Dawson
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to format output of a String using /t so that when resultset is read into hashmap & printed out then it will be displayed in an email in 2 neatly aligned columns. Problem is that when the field of column one is too big it shoves the whole row across no matter how many /ts I use. Please help this seems such a simple problem but I can find no help.
 
Campbell Ritchie
Sheriff
Posts: 48394
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried the format methods? They live in PrintStream, String and Formatter, and probably all use Formatter. The PrintStream#printf method is very similar. You can use the width tags to set all the fields to appropriate widths, then you don't need to use \t.
There are full details in the Formatter documentation.
 
Mike Dawson
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell,
Im having problems using this formatter class do y ou know of any code examples online that I couild look at I cant see any. Basically trying to populate two columns froma hasmap
 
Campbell Ritchie
Sheriff
Posts: 48394
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Start off with something like

System.out.printf("%20s%25s%n", name, address);

See how that works.
Try the flags shown in the Formatter class. There are a few examples in the Formatter class API, which I think I quoted earlier.

You can set up a Formatter to format to a file (see the Formatter class constructor) and write a similar format with the format method, but beware: as far as I can tell Formatter is only available in overwrite mode, not append mode.
 
Mike Dawson
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic