Domanda

I need an equivalent behaviour in java for this command in Unix cli:

ls /data/archive/users/*/*.xml

Which outputs me:

/data/archive/users/2012/user1.xml
/data/archive/users/2013/user2.xml

Is there a simple equivalent implementation for Java 6?

È stato utile?

Soluzione 4

Here is the code I used, it works with relative and absolute paths:

DirectoryScanner scanner = new DirectoryScanner();  
if (!inputPath.startsWith("/") || inputPath.startsWith(".")) {  
    scanner.setBasedir(".");  
}  
scanner.setIncludes(new String[]{inputPath});  
scanner.setCaseSensitive(false);  
scanner.scan();  
String[] foundFiles = scanner.getIncludedFiles();

(DirectoryScanner from org.apache.tools.ant)

Altri suggerimenti

Get user input using java.util.Scanner and use java.io.File.listFiles(FilenameFilter) method to get the list of files in the folder with specific filter.

Yes, there is, and it's called the list method of the File class. See it's Javadoc for details.

I forget where this came from but this should be a good start. There are many more available via Google.

public class RegexFilenameFilter implements FilenameFilter {
  /**
   * Only file name that match this regex are accepted by this filter
   */
  String regex = null; // setting the filter regex to null causes any name to be accepted (same as ".*")

  public RegexFilenameFilter() {
  }

  public RegexFilenameFilter(String filter) {
    setWildcard(filter);
  }

  /**
   * Set the filter from a wildcard expression as known from the windows command line
   * ("?" = "any character", "*" = zero or more occurances of any character")
   *
   * @param sWild the wildcard pattern
   *
   * @return this
   */
  public RegexFilenameFilter setWildcard(String sWild) {
    regex = wildcardToRegex(sWild);

    // throw PatternSyntaxException if the pattern is not valid
    // this should never happen if wildcardToRegex works as intended,
    // so thiw method does not declare PatternSyntaxException to be thrown
    Pattern.compile(regex);
    return this;
  }

  /**
   * Set the regular expression of the filter
   *
   * @param regex the regular expression of the filter
   *
   * @return this
   */
  public RegexFilenameFilter setRegex(String regex) throws java.util.regex.PatternSyntaxException {
    this.regex = regex;
    // throw PatternSyntaxException if the pattern is not valid
    Pattern.compile(regex);

    return this;
  }

  /**
   * Tests if a specified file should be included in a file list.
   *
   * @param dir the directory in which the file was found.
   *
   * @param name the name of the file.
   *
   * @return true if and only if the name should be included in the file list; false otherwise.
   */
  public boolean accept(File dir, String name) {
    boolean bAccept = false;

    if (regex == null) {
      bAccept = true;
    } else {
      bAccept = name.toLowerCase().matches(regex);
    }

    return bAccept;
  }

  /**
   * Converts a windows wildcard pattern to a regex pattern
   *
   * @param wild - Wildcard patter containing * and ?
   *
   * @return - a regex pattern that is equivalent to the windows wildcard pattern
   */
  private static String wildcardToRegex(String wild) {
    if (wild == null) {
      return null;
    }
    StringBuilder buffer = new StringBuilder();

    char[] chars = wild.toLowerCase().toCharArray();

    for (int i = 0; i < chars.length; ++i) {
      if (chars[i] == '*') {
        buffer.append(".*");
      } else if (chars[i] == '?') {
        buffer.append('.');
      } else if (chars[i] == ';') {
        buffer.append('|');
      } else if ("+()^$.{}[]|\\".indexOf(chars[i]) != -1) {
        buffer.append('\\').append(chars[i]); // prefix all metacharacters with backslash
      } else {
        buffer.append(chars[i]);
      }
    }

    return buffer.toString();
  }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top