开发者

cleanly lining up output

I have a text file that contains data that was saved using the cvs encryption and I want to open it in java and display it lined up perfectly. I have come开发者_开发技巧 to the point of reading it from the text file but now I want it to be split at the commas and now I want to display it all perfectly aligned.

 Last, First, car year, car model 
 barry, john, 1956, chevy impala 

and I want it to display like this:

 last      First   car year    car model 
 barry     john    1956       chevy impala

and I am just using the scanner class to get the data from the text file.


Determine the max lengths of the column values (including column headers), then create a format String and use that format string to build the aligned rows:

// some easy magic first
String[][] values = getCsvValues(file);
int[] maxLengths = determineMaxLengths(values);

// create formatstring, something like "%10s %5s %10s %n"
StringBuilder formatBuilder = new StringBuilder();
for (int maxLength:maxLengths)
  formatBuilder.append("%").append(maxLength).append("s ");
formatBuilder.append("%n");   // newline

// output
for (String[] row:values)
  System.out.printf(formatBuilder.toString, row);


depending on how certain you need to be that it all lines up, you might have to go through and find the longest string for each column, but I would use tabs: "\t". Two or three between columns usually works for me, for simple debugging that's what I use.

If you're really serious about it being right all the way down, try looking at Formatters and printf.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜