2

I have text file having multiple rows of data.here I want to align all the rows properly.suppose take below scenario.

John.      12345
Steve.         32456
Mike.               62345

Based on above data,32456 and 62345 should align with 12345 properly.I want to do this with java.any clues on this.

Thanks Chaitu

adarshr
  • 57,189
  • 21
  • 133
  • 158
user569125
  • 1,395
  • 12
  • 26
  • 40
  • Do you produce the text file yourself or it exists already and you just want to format it? – Kris Feb 06 '12 at 10:25
  • Here I am trying to read first row reversely and trying to find the position of last row.based on that planning to set the second,third – user569125 Feb 06 '12 at 10:25
  • Take a look at [this](http://stackoverflow.com/questions/388461/how-can-i-pad-a-string-in-java) and [that](http://stackoverflow.com/questions/6080390/java-string-align-to-right). – adarshr Feb 06 '12 at 10:26
  • 1
    Kris:I am getting that data from db and writing into the text file, before I do this. I have to format it properly – user569125 Feb 06 '12 at 10:27
  • Adarshr: I don't know before whether I can do left or right pad initially – user569125 Feb 06 '12 at 10:30

1 Answers1

4

IF your output is going to be displayed in fixed-width fonts, then you can use the java.util.Formatter class and give each output string a width to line them up. String.format uses the Formatter format syntax:

for (ScoreObject score : scoreList)
{
  String.format("%20s %15s", score.getName(), score.getScore());
}

But you don't say where your output is going, or whether you are using a fixed-width font, etc., so I can only hope this is what you're asking.

arcy
  • 11,973
  • 8
  • 54
  • 89
  • 2
    If there are variable width fonts about but you can set tab widths, just writing everything out with tabs as separators can be good enough. – Donal Fellows Feb 06 '12 at 12:02