Remove all blank lines from a string. - Java java.lang

Java examples for java.lang:String Strip

Description

Remove all blank lines from a string.

Demo Code


import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Locale;
import java.util.SortedSet;
import java.util.TreeSet;

public class Main{
    private static Log log = Log.getLog(JavascriptUtil.class);
    /**/*from w w  w  .  j  av  a  2 s .c o  m*/
     * Remove all blank lines from a string.
     * A blank line is defined to be a line where the only characters are whitespace.
     * We always ensure that the line contains a newline at the end.
     * @param text The string to strip blank lines from
     * @return The blank line stripped reply
     */
    public static String stripBlankLines(String text) {
        if (text == null) {
            return null;
        }

        try {
            StringBuffer output = new StringBuffer();

            BufferedReader in = new BufferedReader(new StringReader(text));
            boolean doneOneLine = false;
            while (true) {
                String line = in.readLine();
                if (line == null) {
                    break;
                }

                if (line.trim().length() > 0) {
                    output.append(line);
                    output.append('\n');
                    doneOneLine = true;
                }
            }

            if (!doneOneLine) {
                output.append('\n');
            }

            return output.toString();
        } catch (IOException ex) {
            log.error("IOExecption unexpected.", ex);
            throw new IllegalArgumentException("IOExecption unexpected.");
        }
    }
}

Related Tutorials