⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stringutils.java

📁 基于Jabber协议的即时消息服务器
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
     * Strings length the string will be returned as is.     * <p/>     * Please note that this method can be lossy - trailing spaces on wrapped     * lines may be trimmed.     *     * @param input the String to reformat.     * @param width the maximum length of any one line.     * @return a new String with reformatted as needed.     */    public static String wordWrap(String input, int width, Locale locale) {        // protect ourselves        if (input == null) {            return "";        }        else if (width < 5) {            return input;        }        else if (width >= input.length()) {            return input;        }        // default locale        if (locale == null) {            locale = JiveGlobals.getLocale();        }        StringBuilder buf = new StringBuilder(input);        boolean endOfLine = false;        int lineStart = 0;        for (int i = 0; i < buf.length(); i++) {            if (buf.charAt(i) == '\n') {                lineStart = i + 1;                endOfLine = true;            }            // handle splitting at width character            if (i > lineStart + width - 1) {                if (!endOfLine) {                    int limit = i - lineStart - 1;                    BreakIterator breaks = BreakIterator.getLineInstance(locale);                    breaks.setText(buf.substring(lineStart, i));                    int end = breaks.last();                    // if the last character in the search string isn't a space,                    // we can't split on it (looks bad). Search for a previous                    // break character                    if (end == limit + 1) {                        if (!Character.isWhitespace(buf.charAt(lineStart + end))) {                            end = breaks.preceding(end - 1);                        }                    }                    // if the last character is a space, replace it with a \n                    if (end != BreakIterator.DONE && end == limit + 1) {                        buf.replace(lineStart + end, lineStart + end + 1, "\n");                        lineStart = lineStart + end;                    }                    // otherwise, just insert a \n                    else if (end != BreakIterator.DONE && end != 0) {                        buf.insert(lineStart + end, '\n');                        lineStart = lineStart + end + 1;                    }                    else {                        buf.insert(i, '\n');                        lineStart = i + 1;                    }                }                else {                    buf.insert(i, '\n');                    lineStart = i + 1;                    endOfLine = false;                }            }        }        return buf.toString();    }    /**     * Escapes all necessary characters in the String so that it can be used in SQL     *     * @param string the string to escape.     * @return the string with appropriate characters escaped.     */    public static String escapeForSQL(String string) {        if (string == null) {            return null;        }        else if (string.length() == 0) {            return string;        }        char ch;        char[] input = string.toCharArray();        int i = 0;        int last = 0;        int len = input.length;        StringBuilder out = null;        for (; i < len; i++) {            ch = input[i];            if (ch == '\'') {                if (out == null) {                     out = new StringBuilder(len + 2);                }                if (i > last) {                    out.append(input, last, i - last);                }                last = i + 1;                out.append('\'').append('\'');            }        }        if (out == null) {            return string;        }        else if (i > last) {            out.append(input, last, i - last);        }        return out.toString();    }    /**     * Escapes all necessary characters in the String so that it can be used     * in an XML doc.     *     * @param string the string to escape.     * @return the string with appropriate characters escaped.     */    public static String escapeForXML(String string) {        if (string == null) {            return null;        }        char ch;        int i = 0;        int last = 0;        char[] input = string.toCharArray();        int len = input.length;        StringBuilder out = new StringBuilder((int)(len * 1.3));        for (; i < len; i++) {            ch = input[i];            if (ch > '>') {            }            else if (ch == '<') {                if (i > last) {                    out.append(input, last, i - last);                }                last = i + 1;                out.append(LT_ENCODE);            }            else if (ch == '&') {                if (i > last) {                    out.append(input, last, i - last);                }                last = i + 1;                out.append(AMP_ENCODE);            }            else if (ch == '"') {                if (i > last) {                    out.append(input, last, i - last);                }                last = i + 1;                out.append(QUOTE_ENCODE);            }        }        if (last == 0) {            return string;        }        if (i > last) {            out.append(input, last, i - last);        }        return out.toString();    }    /**     * Unescapes the String by converting XML escape sequences back into normal     * characters.     *     * @param string the string to unescape.     * @return the string with appropriate characters unescaped.     */    public static String unescapeFromXML(String string) {        string = replace(string, "&lt;", "<");        string = replace(string, "&gt;", ">");        string = replace(string, "&quot;", "\"");        return replace(string, "&amp;", "&");    }    private static final char[] zeroArray =            "0000000000000000000000000000000000000000000000000000000000000000".toCharArray();    /**     * Pads the supplied String with 0's to the specified length and returns     * the result as a new String. For example, if the initial String is     * "9999" and the desired length is 8, the result would be "00009999".     * This type of padding is useful for creating numerical values that need     * to be stored and sorted as character data. Note: the current     * implementation of this method allows for a maximum <tt>length</tt> of     * 64.     *     * @param string the original String to pad.     * @param length the desired length of the new padded String.     * @return a new String padded with the required number of 0's.     */    public static String zeroPadString(String string, int length) {        if (string == null || string.length() > length) {            return string;        }        StringBuilder buf = new StringBuilder(length);        buf.append(zeroArray, 0, length - string.length()).append(string);        return buf.toString();    }    /**     * Formats a Date as a fifteen character long String made up of the Date's     * padded millisecond value.     *     * @return a Date encoded as a String.     */    public static String dateToMillis(Date date) {        return zeroPadString(Long.toString(date.getTime()), 15);    }    /**     * Returns a textual representation for the time that has elapsed.     *     * @param delta the elapsed time.     * @return textual representation for the time that has elapsed.     */    public static String getElapsedTime(long delta) {        if (delta < JiveConstants.MINUTE) {            return LocaleUtils.getLocalizedString("global.less-minute");        }        else if (delta < JiveConstants.HOUR) {            long mins = delta / JiveConstants.MINUTE;            StringBuilder sb = new StringBuilder();            sb.append(mins).append(" ");            sb.append((mins==1) ? LocaleUtils.getLocalizedString("global.minute") : LocaleUtils.getLocalizedString("global.minutes"));            return sb.toString();        }        else if (delta < JiveConstants.DAY) {            long hours = delta / JiveConstants.HOUR;            delta -= hours * JiveConstants.HOUR;            long mins = delta / JiveConstants.MINUTE;            StringBuilder sb = new StringBuilder();            sb.append(hours).append(" ");            sb.append((hours == 1) ? LocaleUtils.getLocalizedString("global.hour") : LocaleUtils.getLocalizedString("global.hours"));            sb.append(", ");            sb.append(mins).append(" ");            sb.append((mins == 1) ? LocaleUtils.getLocalizedString("global.minute") : LocaleUtils.getLocalizedString("global.minutes"));            return sb.toString();        } else {            long days = delta / JiveConstants.DAY;            delta -= days * JiveConstants.DAY;            long hours = delta / JiveConstants.HOUR;            delta -= hours * JiveConstants.HOUR;            long mins = delta / JiveConstants.MINUTE;            StringBuilder sb = new StringBuilder();            sb.append(days).append(" ");            sb.append((days == 1) ? LocaleUtils.getLocalizedString("global.day") : LocaleUtils.getLocalizedString("global.days"));            sb.append(", ");            sb.append(hours).append(" ");            sb.append((hours == 1) ? LocaleUtils.getLocalizedString("global.hour") : LocaleUtils.getLocalizedString("global.hours"));            sb.append(", ");            sb.append(mins).append(" ");            sb.append((mins == 1) ? LocaleUtils.getLocalizedString("global.minute") : LocaleUtils.getLocalizedString("global.minutes"));            return sb.toString();        }    }    /**     * Returns a collection of Strings as a comma-delimitted list of strings.     *     * @return a String representing the Collection.     */    public static String collectionToString(Collection<String> collection) {        if (collection == null || collection.isEmpty()) {            return "";        }        StringBuilder buf = new StringBuilder();        String delim = "";        for (String element : collection) {            buf.append(delim);            buf.append(element);            delim = ",";        }        return buf.toString();    }    /**     * Returns a comma-delimitted list of Strings as a Collection.     *     * @return a Collection representing the String.     */    public static Collection<String> stringToCollection(String string) {        if (string == null || string.trim().length() == 0) {            return Collections.emptyList();        }        Collection<String> collection = new ArrayList<String>();        StringTokenizer tokens = new StringTokenizer(string, ",");        while (tokens.hasMoreTokens()) {            collection.add(tokens.nextToken().trim());        }        return collection;    }    /**     * Abbreviates a string to a specified length and then adds an ellipsis     * if the input is greater than the maxWidth. Example input:     * <pre>     *      user1@jivesoftware.com/home     * </pre>     * and a maximum length of 20 characters, the abbreviate method will return:     * <pre>     *      user1@jivesoftware.c...     * </pre>     * @param str the String to abbreviate.     * @param maxWidth the maximum size of the string, minus the ellipsis.     * @return the abbreviated String, or <tt>null</tt> if the string was <tt>null</tt>.     */    public static String abbreviate(String str, int maxWidth) {        if (null == str) {            return null;        }        if (str.length() <= maxWidth) {            return str;        }                return str.substring(0, maxWidth) + "...";    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -