【问题标题】:unix 'ls' command with wildcard input - equivalent in java 6带有通配符输入的 unix 'ls' 命令 - 在 java 6 中等效
【发布时间】:2013-03-17 12:01:22
【问题描述】:

对于 Unix cli 中的这个命令,我需要 java 中的等效行为:

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

哪个输出我:

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

是否有 Java 6 的简单等效实现?

【问题讨论】:

    标签: java unix wildcard ls


    【解决方案1】:

    使用java.util.Scanner 获取用户输入,并使用java.io.File.listFiles(FilenameFilter) 方法获取具有特定过滤器的文件夹中的文件列表。

    【讨论】:

    • ex 的解析不是那么容易。路径:“/data/*/users/*/*.xml”。有没有更简单的方法?
    【解决方案2】:

    是的,有,它被称为File 类的list 方法。详情请见Javadoc

    【讨论】:

      【解决方案3】:

      我忘记了这是从哪里来的,但这应该是一个好的开始。还有更多可以通过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();
        }
      }
      

      【讨论】:

        【解决方案4】:

        这是我使用的代码,它适用于相对路径和绝对路径:

        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();
        

        (来自 org.apache.tools.ant 的 DirectoryScanner)

        【讨论】:

          猜你喜欢
          • 2012-04-21
          • 2012-06-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-28
          • 2013-01-22
          • 2014-08-17
          相关资源
          最近更新 更多