package org.cass; import java.io.*; import java.util.regex.*; /** A class containing useful parsing tools, file pattern generation and filtration, and a host of other utilities. @author Zachary Vaughan @version 1.1 07/14/06 */ public class Utilities { /** Extracts the parent directory portion of the given file pattern. The final directory path separator character is also included (typically the forward or backward slash).

Note that this method assumes the directory portion is made up of legal directory name characters for the underlying filesystem and no wildcard characters. No warnings or exceptions are thrown if this is violated. It is up to the user to determine the validity of the string beforehand and he or she sees fit.

@param pstr the pattern string to parse. @throws NullPointerException if str is null. @return the parent directory portion of the given pattern string, or the empty string if none is present in the pattern. @see #parsePattern(String) parsePattern(str) */ public static String parseDirectory(String pstr) { int i = pstr.lastIndexOf(File.separator); return i == -1 ? "." + File.separator : pstr.substring(0, i + 1); } /** Extracts the pattern portion of the given file pattern by trimming off the preceding directory portion. In effect this method extracts the opposite from the given pattern as the parseDirectory() method.

Note that this method assumes the pattern portion is made up of legal file name characters for the underlying filesystem and legal wildcard characters. No warnings or exceptions are thrown if this is violated. It is up to the user to determine the validity of the string beforehand and he or she sees fit.

@param pstr the pattern string to parse. @throws NullPointerException if str is null. @return the pattern portion of the given pattern string. @see #parseDirectory(String) parseDirectory(str) */ public static String parsePattern(String pstr) { return pstr.substring(pstr.lastIndexOf(File.separator) + 1); } /** Gets the set of files matching the given file pattern string. @param pstr the file pattern string to use. @return an array of files matching the given pattern string, in no particular order, or null if the given pattern string does not denote a valid directory to search. */ public static File[] getFiles(String pstr) { File dir = new File(parseDirectory(pstr)); String pat = parsePattern(pstr); final Pattern p = Pattern.compile( pat.replace(".", "\\.").replace("*", ".*")); return dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return p.matcher(name).matches(); } }); } private Utilities() {} }