Remove any leading or trailing spaces from a line of code. - Java java.lang

Java examples for java.lang:String Strip

Description

Remove any leading or trailing spaces from a line of code.

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);
    /**/*  ww  w.j  a v a2s.  c  o  m*/
     * Remove any leading or trailing spaces from a line of code.
     * This function could be improved by making it strip unnecessary double
     * spaces, but since we would need to leave double spaces inside strings
     * this is not simple and since the benefit is small, we'll leave it for now
     * @param text The javascript program to strip spaces from.
     * @return The stripped program
     */
    public static String trimLines(String text) {
        if (text == null) {
            return null;
        }

        try {
            StringBuffer output = new StringBuffer();

            // First we strip multi line comments. I think this is important:
            BufferedReader in = new BufferedReader(new StringReader(text));
            while (true) {
                String line = in.readLine();
                if (line == null) {
                    break;
                }

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

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

Related Tutorials