简体   繁体   English

Java中的延迟打印

[英]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? 我了解上述可能性极有可能达到99.99999%,但也许你们有达到上述目标的聪明方法?

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. 您可以将PrintStream包裹在ByteArrayOutputStream周围,​​然后使用该PrintStream代替System.out (或使用System.setOut )进行打印。 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. 最好将db中的所有单元格收集到一个数组中并计算最大长度,然后打印该数组。

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. 但这实际上取决于您的问题领域,哪种方法最好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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