bumbleshoot
bumbleshoot

Reputation: 1160

Java: how can I format text on an OutputStream to the width of the user's console?

Specifically, I would like text sent to the user's OutputStream to have word wrapping so that when text continues onto a new line, words are not broken up. So instead of this:

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

It will show up in the console like this:

The quick brown fox 
jumps over the lazy 
dog.

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

wrapText(String text, int width)

But I'd rather have the text just wrap automatically to the current width of the user's console. Is there any way to do this? Any objects in java that might help me? Thanks!

Upvotes: 4

Views: 1865

Answers (2)

prunge
prunge

Reputation: 23248

To get the width of the console, you can use the JLine library. It's not pure Java and has some native code, but has the functionality you need and works on Windows, Max and Linux.

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

Upvotes: 2

Edward Samson
Edward Samson

Reputation: 2425

A BreakIterator would help you determine where to break lines and from there it would be easy go to doing the actual line breaking yourself.

However, I don't see how you'd determine (automatically, cross-platform) the width of the user's console.

Upvotes: 3

Related Questions