|
Java example source code file (StringUtils.java)
The StringUtils.java Java example source code/* * * * Copyright 2015 Skymind,Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package org.deeplearning4j.berkeley; import java.io.*; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * StringUtils is a class for random String things. * * @author Dan Klein * @author Christopher Manning * @author Tim Grow (grow@stanford.edu) * @author Chris Cox * @version 2003/02/03 */ public class StringUtils { /** * Don't let anyone instantiate this class. */ private StringUtils() { } /** * Say whether this regular expression can be found inside * this String. This method provides one of the two "missing" * convenience methods for regular expressions in the String class * in JDK1.4. This is the one you'll want to use all the time if * you're used to Perl. What were they smoking? * * @param str String to search for match in * @param regex String to compile as the regular expression * @return Whether the regex can be found in str */ public static boolean find(String str, String regex) { return Pattern.compile(regex).matcher(str).find(); } /** * Say whether this regular expression can be found at the beginning of * this String. This method provides one of the two "missing" * convenience methods for regular expressions in the String class * in JDK1.4. * * @param str String to search for match at start of * @param regex String to compile as the regular expression * @return Whether the regex can be found at the start of str */ public static boolean lookingAt(String str, String regex) { return Pattern.compile(regex).matcher(str).lookingAt(); } /** * Say whether this regular expression matches * this String. This method is the same as the String.matches() method, * and is included just to give a call that is parallel to the other * static regex methods in this class. * * @param str String to search for match at start of * @param regex String to compile as the regular expression * @return Whether the regex matches the whole of this str */ public static boolean matches(String str, String regex) { return Pattern.compile(regex).matcher(str).matches(); } private static final int SLURPBUFFSIZE = 16000; /** * Returns all the text in the given File. */ public static String slurpFile(File file) throws IOException { Reader r = new FileReader(file); return slurpReader(r); } public static String slurpGBFileNoExceptions(String filename) { return slurpFileNoExceptions(filename, "GB18030"); } /** * Returns all the text in the given file with the given encoding. */ public static String slurpFile(String filename, String encoding) throws IOException { Reader r = new InputStreamReader(new FileInputStream(filename), encoding); return slurpReader(r); } /** * Returns all the text in the given file with the given encoding. * If the file cannot be read (non-existent, etc.), * then and only then the method returns <code>null. */ public static String slurpFileNoExceptions(String filename, String encoding) { try { return slurpFile(filename, encoding); } catch (Exception e) { throw new RuntimeException(); } } public static String slurpGBFile(String filename) throws IOException { return slurpFile(filename, "GB18030"); } /** * Returns all the text from the given Reader. * * @return The text in the file. */ public static String slurpReader(Reader reader) { BufferedReader r = new BufferedReader(reader); StringBuffer buff = new StringBuffer(); try { char[] chars = new char[SLURPBUFFSIZE]; while (true) { int amountRead = r.read(chars, 0, SLURPBUFFSIZE); if (amountRead < 0) { break; } buff.append(chars, 0, amountRead); } r.close(); } catch (Exception e) { throw new RuntimeException(); } return buff.toString(); } /** * Returns all the text in the given file * * @return The text in the file. */ public static String slurpFile(String filename) throws IOException { return slurpReader(new FileReader(filename)); } /** * Returns all the text in the given File. * * @return The text in the file. May be an empty string if the file * is empty. If the file cannot be read (non-existent, etc.), * then and only then the method returns <code>null. */ public static String slurpFileNoExceptions(File file) { try { return slurpReader(new FileReader(file)); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Returns all the text in the given File. * * @return The text in the file. May be an empty string if the file * is empty. If the file cannot be read (non-existent, etc.), * then and only then the method returns <code>null. */ public static String slurpFileNoExceptions(String filename) { try { return slurpFile(filename); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Returns all the text at the given URL. */ public static String slurpGBURL(URL u) throws IOException { return slurpURL(u, "GB18030"); } /** * Returns all the text at the given URL. */ public static String slurpGBURLNoExceptions(URL u) { try { return slurpGBURL(u); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Returns all the text at the given URL. */ public static String slurpURLNoExceptions(URL u, String encoding) { try { return slurpURL(u, encoding); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Returns all the text at the given URL. */ public static String slurpURL(URL u, String encoding) throws IOException { String lineSeparator = System.getProperty("line.separator"); URLConnection uc = u.openConnection(); uc.setReadTimeout(30000); InputStream is; try { is = uc.getInputStream(); } catch (SocketTimeoutException e) { //e.printStackTrace(); System.err.println("Time out. Return empty string"); return ""; } BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding)); String temp; StringBuffer buff = new StringBuffer(16000); // make biggish while ((temp = br.readLine()) != null) { buff.append(temp); buff.append(lineSeparator); } br.close(); return buff.toString(); } /** * Returns all the text at the given URL. */ public static String slurpURL(URL u) throws IOException { String lineSeparator = System.getProperty("line.separator"); URLConnection uc = u.openConnection(); InputStream is = uc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String temp; StringBuffer buff = new StringBuffer(16000); // make biggish while ((temp = br.readLine()) != null) { buff.append(temp); buff.append(lineSeparator); } br.close(); return buff.toString(); } /** * Returns all the text at the given URL. */ public static String slurpURLNoExceptions(URL u) { try { return slurpURL(u); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Returns all the text at the given URL. */ public static String slurpURL(String path) throws Exception { return slurpURL(new URL(path)); } /** * Returns all the text at the given URL. If the file cannot be read (non-existent, etc.), * then and only then the method returns <code>null. */ public static String slurpURLNoExceptions(String path) { try { return slurpURL(path); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Joins each elem in the Collection with the given glue. For example, given a * list * of Integers, you can createComplex a comma-separated list by calling * <tt>join(numbers, ", "). */ public static String join(Iterable l, String glue) { StringBuffer sb = new StringBuffer(); boolean first = true; for (Object o : l) { if (!first) { sb.append(glue); } sb.append(o.toString()); first = false; } return sb.toString(); } /** * Joins each elem in the List with the given glue. For example, given a * list * of Integers, you can createComplex a comma-separated list by calling * <tt>join(numbers, ", "). */ public static String join(List<?> l, String glue) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < l.size(); i++) { if (i > 0) { sb.append(glue); } Object x = l.get(i); sb.append(x.toString()); } return sb.toString(); } /** * Joins each elem in the array with the given glue. For example, given a list * of ints, you can createComplex a comma-separated list by calling * <tt>join(numbers, ", "). */ public static String join(Object[] elements, String glue) { return (join(Arrays.asList(elements), glue)); } /** * Joins elems with a space. */ public static String join(List l) { return join(l, " "); } /** * Joins elems with a space. */ public static String join(Object[] elements) { return (join(elements, " ")); } /** * Splits on whitespace (\\s+). */ public static List split(String s) { return (split(s, "\\s+")); } /** * Splits the given string using the given regex as delimiters. * This method is the same as the String.split() method (except it throws * the results in a List), * and is included just to give a call that is parallel to the other * static regex methods in this class. * * @param str String to split up * @param regex String to compile as the regular expression * @return List of Strings resulting from splitting on the regex */ public static List split(String str, String regex) { return (Arrays.asList(str.split(regex))); } /** * Return a String of length a minimum of totalChars characters by * padding the input String str with spaces. If str is already longer * than totalChars, it is returned unchanged. */ public static String pad(String str, int totalChars) { if (str == null) str = "null"; int slen = str.length(); StringBuffer sb = new StringBuffer(str); for (int i = 0; i < totalChars - slen; i++) { sb.append(" "); } return sb.toString(); } /** * Pads the toString value of the given Object. */ public static String pad(Object obj, int totalChars) { return pad(obj.toString(), totalChars); } /** * Pad or trim so as to produce a string of exactly a certain length. * * @param str The String to be padded or truncated * @param num The desired length */ public static String padOrTrim(String str, int num) { if (str == null) str = "null"; int leng = str.length(); if (leng < num) { StringBuffer sb = new StringBuffer(str); for (int i = 0; i < num - leng; i++) { sb.append(" "); } return sb.toString(); } else if (leng > num) { return str.substring(0, num); } else { return str; } } /** * Pad or trim the toString value of the given Object. */ public static String padOrTrim(Object obj, int totalChars) { return padOrTrim(obj.toString(), totalChars); } /** * Pads the given String to the left with spaces to ensure that it's * at least totalChars long. */ public static String padLeft(String str, int totalChars) { if (str == null) str = "null"; StringBuffer sb = new StringBuffer(); for (int i = 0; i < totalChars - str.length(); i++) { sb.append(" "); } sb.append(str); return sb.toString(); } public static String padLeft(Object obj, int totalChars) { return padLeft(obj.toString(), totalChars); } public static String padLeft(int i, int totalChars) { return padLeft(new Integer(i), totalChars); } public static String padLeft(double d, int totalChars) { return padLeft(new Double(d), totalChars); } /** * Returns s if it's at most maxWidth chars, otherwise chops right side to fit. */ public static String trim(String s, int maxWidth) { if (s.length() <= maxWidth) { return (s); } return (s.substring(0, maxWidth)); } public static String trim(Object obj, int maxWidth) { return trim(obj.toString(), maxWidth); } /** * Returns a "clean" version of the given filename in which spaces have * been converted to dashes and all non-alphaneumeric chars are underscores. */ public static String fileNameClean(String s) { char[] chars = s.toCharArray(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_')) { sb.append(c); } else { if (c == ' ' || c == '-') { sb.append('_'); } else { sb.append("x" + (int) c + "x"); } } } return sb.toString(); } /** * Returns the index of the <i>nth occurrence of ch in s, or -1 * if there are less than n occurrences of ch. */ public static int nthIndex(String s, char ch, int n) { int index = 0; for (int i = 0; i < n; i++) { // if we're already at the end of the string, // and we need to find another ch, return -1 if (index == s.length() - 1) { return -1; } index = s.indexOf(ch, index + 1); if (index == -1) { return (-1); } } return index; } /** * This returns a string from decimal digit smallestDigit to decimal digit * biggest digit. Smallest digit is labeled 1, and the limits are * inclusive. */ public static String truncate(int n, int smallestDigit, int biggestDigit) { int numDigits = biggestDigit - smallestDigit + 1; char[] result = new char[numDigits]; for (int j = 1; j < smallestDigit; j++) { n = n / 10; } for (int j = numDigits - 1; j >= 0; j--) { result[j] = Character.forDigit(n % 10, 10); n = n / 10; } return new String(result); } /** * Parses command line arguments into a Map. Arguments of the form * <p/> * -flag1 arg1a arg1b ... arg1m -flag2 -flag3 arg3a ... arg3n * <p/> * will be parsed so that the flag is a key in the Map (including * the hyphen) and its value will be a {@link String[] } containing * the optional arguments (if present). The non-flag values not * captured as flag arguments are collected into a String[] array * and returned as the value of <code>null in the Map. In * this invocation, flags cannot take arguments, so all the {@link * String} array values other than the value for <code>null * will be zero-length. * * @param args * @return a {@link Map} of flag names to flag argument {@link * String[]} arrays. */ public static Map<String, String[]> argsToMap(String[] args) { return argsToMap(args, new HashMap<String, Integer>()); } /** * Parses command line arguments into a Map. Arguments of the form * <p/> * -flag1 arg1a arg1b ... arg1m -flag2 -flag3 arg3a ... arg3n * <p/> * will be parsed so that the flag is a key in the Map (including * the hyphen) and its value will be a {@link String[] } containing * the optional arguments (if present). The non-flag values not * captured as flag arguments are collected into a String[] array * and returned as the value of <code>null in the Map. In * this invocation, the maximum number of arguments for each flag * can be specified as an {@link Integer} value of the appropriate * flag key in the <code>flagsToNumArgs {@link Map} * argument. (By default, flags cannot take arguments.) * <p/> * Example of usage: * <p/> * <code> * Map flagsToNumArgs = new HashMap(); * flagsToNumArgs.put("-x",new Integer(2)); * flagsToNumArgs.put("-d",new Integer(1)); * Map result = argsToMap(args,flagsToNumArgs); * </code> * * @param args the argument array to be parsed * @param flagsToNumArgs a {@link Map} of flag names to {@link * Integer} values specifying the maximum number of allowed * arguments for that flag (default 0). * @return a {@link Map} of flag names to flag argument {@link * String[]} arrays. */ public static Map<String, String[]> argsToMap(String[] args, Map<String, Integer> flagsToNumArgs) { Map<String, String[]> result = new HashMap Other Java examples (source code examples)Here is a short list of links related to this Java StringUtils.java source code file: |
... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.