Skip to content

Instantly share code, notes, and snippets.

@aembleton
Created May 19, 2011 10:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aembleton/980518 to your computer and use it in GitHub Desktop.
Save aembleton/980518 to your computer and use it in GitHub Desktop.
Useful String utility methods.
package utils;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Useful String utility methods.
*
* @author arthur
*
*/
public class StringUtil {
private static final Logger log = LoggerFactory.getLogger(StringUtil.class);
/**
* Determines if a given String is null or empty.
*
* @param string
* The String to test
* @return true if string is null or empty.
*/
public static boolean isNullOrEmpty(String string) {
return string == null || string.trim().length() == 0;
}
/**
* Determines if all of the strings are not null or empty. In other words, all of the strings are set and contain at least one non-whitespace character.
*
* @param strings
* An array of strings to check
* @return true if all of the strings have been set
*/
public static boolean allHaveValues(String... strings) {
for (String string : strings) {
if (isNullOrEmpty(string)) {
return false;
}
}
return true;
}
/**
* Converts an {@link InputStream} into a String.
*
* @param inputStream
* The input stream to convert
* @return A String containing the contents of the {@link InputStream}
*/
public static String fromInputStream(InputStream inputStream) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
return fromBufferedReader(bufferedReader);
}
/**
* Converts a {@link BufferedReader} into a String.
*
* @param bufferedReader
* The {@link BufferedReader} to convert
* @return A String containing the contents of the {@link BufferedReader}
*/
public static String fromBufferedReader(BufferedReader bufferedReader) {
StringBuffer sb = new StringBuffer();
try {
String line = bufferedReader.readLine();
while (line != null) {
sb.append(line);
line = bufferedReader.readLine();
if (line != null) {
sb.append("\n");
}
}
} catch (IOException e) {
log.error("Could not read in a line from the BufferedReader.", e);
}
return sb.toString();
}
/**
* Reads a file into a {@link LinkedList}. Unlike with a properties file, this preserves the ordering.
*
* @param fileName
* fileName to read in
* @return A {@link LinkedList} of {@link String}s. null if the file could not be read in
*/
public static LinkedList<String> fromFile(String fileName) {
LinkedList<String> list = new LinkedList<String>();
try {
InputStream fileInputStream = StringUtil.class.getResourceAsStream("/" + fileName);
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));
String strLine;
while ((strLine = bufferedReader.readLine()) != null) {
list.add(strLine);
}
} catch (FileNotFoundException e) {
log.error("Could not find the file:" + fileName);
log.error("Classpath:" + getAllFilesOnClasspath());
} catch (IOException e) {
log.error("Could not read in the file:" + fileName);
}
return list;
}
public static String getClasspath() {
Properties prop = System.getProperties();
return prop.getProperty("java.class.path", null);
}
public static String getAllFilesOnClasspath() {
StringBuffer sb = new StringBuffer();
for (final java.lang.String path : getClasspath().split(":")) {
final java.io.File object = new java.io.File(path);
if (object.isDirectory()) {
for (File file : object.listFiles()) {
sb.append(file.getAbsolutePath()).append("\n");
}
} else if (object.isFile()) {
sb.append(object).append("\n");
}
}
return sb.toString();
}
/**
* Converts a 2 dimensional array into a map where the first dimension is 2 cell String array containing key and value respectively. Any array with fewer than 2 elements is ignored.
*
* @param array
* The array to convert into a map
* @return A {@link Map} of key value pairs extracted from the supplied array.
*/
public static Map<String, String> arrayToMap(String[][] array) {
Map<String, String> map = new HashMap<String, String>();
for (String[] pair : array) {
if (pair.length > 1) {
// got a pair, add to map
map.put(pair[0], pair[1]);
}
}
return map;
}
/**
* Searches through a given String array and returns an element that starts with the supplied startsWith string. This method ignores the case. If no match can be found then an empty String is
* returned.
*
* @param array
* The array of Strings to search through
* @param startsWith
* The String to match.
* @return A String that starts with startsWith (ignoring case) or an empty String if one cannot be found. If multiple Strings match, then the first one in the array will be returned.
*/
public static String startsWith(String[] array, String startsWith) {
String lcStartsWith = startsWith.toLowerCase();
for (String element : array) {
if (element.toLowerCase().startsWith(lcStartsWith)) {
return element;
}
}
log.warn("Could not find any element that starts with " + startsWith);
return "";
}
/**
* Iterates over the array looking for an element that, ignoring case starts with the startsWith string. If a match is found then the index of the matching element is returned. If no match is
* found then -1 is returned.
*
* @param array
* The array of String to search through.
* @param startsWith
* The String to match against
* @return Index of the matching element, or -1 if no match is found. If there are multiple matches then the index of the first match is returned.
*/
public static int indexThatStartsWith(String[] array, String startsWith) {
String lcStartsWith = startsWith.toLowerCase();
for (int i = 0; i < array.length; i++) {
if (array[i].toLowerCase().startsWith(lcStartsWith)) {
return i;
}
}
log.warn("Could not find any element that starts with " + startsWith);
return -1;
}
/**
* Keeps prepending a given prependChar to an initialInt until it reaches the targetLength and returns the result. If initialInt is null then null is returned.
*
* @param prependChar
* The char to prepend
* @param targetLength
* The targetLength
* @param initialInt
* The initial Integer
* @return The initialInt padded out with the prependChar at the beginning of the string until it reaches the targetLength
*/
public static String prependToLength(char prependChar, int targetLength, Integer initialInt) {
if (initialInt == null) {
return null;
}
return prependToLength(prependChar, targetLength, initialInt.toString());
}
/**
* Keeps prepending a given prependChar to an initialString until it reaches the targetLength and returns the result. If initialString is null then null is returned.
*
* @param prependChar
* The char to prepend
* @param targetLength
* The targetLength
* @param initialString
* The initiatlString
* @return The initialString padded out with the prependChar at the beginning of the string until it reaches the targetLength
*/
public static String prependToLength(char prependChar, int targetLength, String initialString) {
if (initialString == null) {
return null;
}
StringBuffer result = new StringBuffer(initialString);
while (result.length() < targetLength) {
result.append(prependChar);
}
return result.reverse().toString();
}
/**
* If a given string is longer than maxLength then it is truncated. For example if str="hamburger" and maxLength=3 then "ham" will be returned.
*
* @param str
* The str to be truncated. If this is null or equal to or shorter than maxLength then it is returned whithout modification.
* @param maxLength
* Maximum length of the returned String. If this is less than 1, then str is returned regardless.
* @return A string no more than maxLength characters in length.
*/
public static String truncate(String str, int maxLength) {
if (str == null || str.length() <= maxLength || maxLength < 1) {
return str;
}
return str.substring(0, maxLength);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment