Remove all newline characters from a string. - Java java.lang

Java examples for java.lang:String Strip

Description

Remove all newline characters 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);
    private static final String SPACE = " ";
    /**/*  w  w w . j ava2s .c  o  m*/
     * Remove all newline characters from a string.
     * @param text The string to strip newline characters from
     * @return The stripped reply
     */
    public static String stripNewlines(String text) {
        if (text == null) {
            return null;
        }

        try {
            StringBuffer output = new StringBuffer();

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

                output.append(line);
                output.append(SPACE);
            }
            output.append('\n');

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

Related Tutorials