简体   繁体   中英

Deferred printing in Java

I have a specific issue with general console printing and I was wondering whether anyone has a solution for it. I am trying to print a dataTable which would look like sth like this:

Table
----------------------
Name    |Surname     |
----------------------
Mike    |Mikhailowish|
Rafaello|Mirena      |

and so on. In order to print the border of the bar I need to know what the maximum length of each column value is. I don't want to go through the whole database to find that out and then again to print it. I would rather like to do sth like:

System.out.printLater(s); //herejust leave a pointer to a StringBuilder you will build
...
s.append("--------");
...
System.out.printAllDeferred();

I understand the above is probably in 99.99999% chances impossible, but perhaps you guys have a clever way of achieving the above?

You can wrap a PrintStream around a ByteArrayOutputStream and then use that PrintStream instead of System.out (or use System.setOut ) to print to it. Later you can print the whole byte array instead.

But that does not really help you since you'll have to adjust all columns; better collect all cells from db into an array and calculate max lengths, then print the array.

Maybe you could find out what would be the maximum length of each column first, if having additional queries doesn't bother you.

for (String name : columnNames) {

    select max(LEN(columnName)) as maxchar from YourTable

}

Otherwise, as others suggest, you could just read the whole table in-memory first, and while doing that calculate the max length of the specific column, depending of whether your heap size is big enough and having the complete table in memory is not a problem.

But It really depends on your problem's domain what approach is best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM