Java code for wrapping text lines to a max line width

Before I re-invent the wheel (poorly), I'd like to know if there is a some existing Java code for wrapping text lines to a given maximum width. Ideally it would:

  • respect existing linebreaks
  • break up lines that exceed a maximum length on word boundaries
  • break up words whose length exceeds the maximum line width by inserting hyphens

Edit: there are no "pixels" here, only java.lang.String. "maximum width" refers to the number of characters on a line.


Apache commons has WordUtils and wrap function in it:

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html

P.S. Looks like this is deprecated and you need to use

https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/WordUtils.html

instead.


Use the word-wrap library (available on Maven Central).

Here's one way to use it:

String text = "hello how are you going?";
String wrapped = 
  WordWrap.from(text)
    .maxWidth(10)
    .insertHyphens(true) // true is the default
    .wrap();

Output is:

hi there
how are
you going?

The library conserves leading spaces on lines which is one complaint about the behaviour of the Apache commons-lang offering. You can also specify the stringWidth function to get pixel-accurate results when rendering the text.

The library has decent unit test coverage (something to bear in mind when you consider copy and paste of code chunks from the web!).

The Maven dependency is:

<dependency>
  <groupId>com.github.davidmoten</groupId>
  <artifactId>word-wrap</artifactId>
  <version>0.1.1</version>
</dependency>

Be sure to check for a later version.