public static String wrapParagraph ( final String input , final int width ) { if ( input == null || input . isEmpty ( ) ) { return input ; } final StringBuilder out = new StringBuilder ( ) ; try ( final BufferedReader bufReader = new BufferedReader ( new StringReader ( input ) ) ) { out . append ( bufReader . lines ( ) . map ( line -> WordUtils . wrap ( line , width ) ) . collect ( Collectors . joining ( "\n" ) ) ) ; } catch ( IOException e ) { throw new RuntimeException ( "Unreachable Statement.\nHow did the Buffered reader throw when it was " + "wrapping a StringReader?" , e ) ; } //if the last character of the input is a newline, we need to add another newline to conserve that. if ( input . charAt ( input . length ( ) - 1 ) == ' ' ) { out . append ( ' ' ) ; } return out . toString ( ) ; }
A utility method to wrap multiple lines of text while respecting the original newlines .