Wrap a line of text into multiple lines in Java using Apache Commons Text

Introduction

In this post we learn how to wrap a String in Java using WordUtils utility class of Apache Commons Text library. By using WordUtils.wrap() method we can break a long line of text into multiple lines with a given input text and the length. The output String will be wrapped words and separated by system line separator character or by your custom provided separator.

Setup Apache Commons Text in Java project

If you are using Gradle build then add the following dependency configuration into build.gradle file.

compile group: 'org.apache.commons', name: 'commons-text', version: '1.9'

Or add the following dependency XML tag to pom.xml file if you are using Maven build.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

Or download commons-text-1.9.jar file from Apache Commons Text download page at commons.apache.org

Wrap words with a given text and wrap length

In this Java code example we use org.apache.commons.text.WordUtils.wrap() method to wrap a long line of text with the provided length to indicate the column to wrap the words.

import org.apache.commons.text.WordUtils;

public class WordUtilsWrapExample1 {
    public static void main(String[] args) {
        String testString = "This is the line of text need to be wrap.";

        String wrappedString = WordUtils.wrap(testString, 20);

        System.out.println(wrappedString);
    }
}
Output:

This is the line of
text need to be
wrap.

Wrap text with provided separator

import org.apache.commons.text.WordUtils;

public class WordUtilsWrapExample2 {
    public static void main(String[] args) {
        String testString = "Click here to go to the Simple Solution website - https://simplesolution.dev/";

        String wrappedString = WordUtils.wrap(testString, 20, "\n", true);

        System.out.println(wrappedString);
    }
}
Output:

Click here to go to
the Simple Solution
website -
https://simplesoluti
on.dev/

Wrap text with the option to not wrapping long words

import org.apache.commons.text.WordUtils;

public class WordUtilsWrapExample3 {
    public static void main(String[] args) {
        String testString = "Click here to go to the Simple Solution website - https://simplesolution.dev/";

        String wrappedString = WordUtils.wrap(testString, 20, "\n", false);

        System.out.println(wrappedString);
    }
}
Output:

Click here to go to
the Simple Solution
website -
https://simplesolution.dev/

Happy Coding 😊