Java: how can I format text in an OutputStream to the width of a user console?

In particular, I would like the text sent to the user of OutputStream to have word wrap, so that when the text goes to a new line, the words are not broken. So instead:

The quick brown fox j umps over the lazy do g. 

It will appear in the console as follows:

 The quick brown fox jumps over the lazy dog. 

One option that I know of is to write a method like this to wrap text to a specific character width:

 wrapText(String text, int width) 

But I would prefer that the text simply automatically snap to the current width of the user console. Is there any way to do this? Any objects in java that can help me? Thanks!

+4
source share
2 answers

A BreakIterator will help you determine where to break the lines, and from there it will be easy to jump to the actual line that violates itself.

However, I do not see how you determine (automatically, cross-platform) the width of the user console.

+3
source

To get the width of the console, you can use the JLine library. It is not pure Java and has its own code, but it has the necessary functionality and works on Windows, Max and Linux.

In JLine, to get the width of the console, use the Terminal class and call getTerminalWidth() .

+2
source

Source: https://habr.com/ru/post/1379909/


All Articles