zoukankan      html  css  js  c++  java
  • FileFilter, FilenameFilter用法和文件排序

    FileFilter和FilenameFilter这两个类的用法都很简单,都只有一个方法


    FileFilter
    /**
    * @param pathname The abstract pathname to be tested
    */

    boolean accept(File pathname)
    用法示例:
    import java.io.File;
    import java.io.FileFilter;

    public class Main {

      public static void main(String[] args) {

        File cwd = new File(System.getProperty("user.dir"));
        File[] htmlFiles = cwd.listFiles(new HTMLFileFilter());
        for (int i = 0; i < htmlFiles.length; i++) {
          System.out.println(htmlFiles[i]);
        }
      }
    }

    class HTMLFileFilter implements FileFilter {

      public boolean accept(File pathname) {

        if (pathname.getName().endsWith(".html"))
          return true;
        if (pathname.getName().endsWith(".htm"))
          return true;
        return false;
      }
    }
     
    FilenameFilter
     
    /**
    * @param dir - the directory in which the file was found.
    * @param name - the name of the file.
    */

    boolean accept(File dir,  String name)
    用法示例:
    import java.io.File;
    import java.io.FilenameFilter;

    class ExtensionFilter implements FilenameFilter {
      String ext;

      public ExtensionFilter(String ext) {
        this.ext = "." + ext;
      }

      public boolean accept(File dir, String name) {
        return name.endsWith(ext);
      }
    }

    public class Main {
      public static void main(String args[]) {
        String dirname = "/java";
        File f1 = new File(dirname);
        FilenameFilter only = new ExtensionFilter("html");
        String s[] = f1.list(only);
        for (int i = 0; i < s.length; i++) {
          System.out.println(s[i]);
        }
      }
    }
     
    文件排序
    排序规则:目录排在前面,按字母顺序排序文件列表
     
    List<File> files = Arrays.asList(new File("<目录>").listFiles());
    Collections.sort(files, new Comparator<File>(){
        @Override
        public int compare(File o1, File o2) {
        if(o1.isDirectory() && o2.isFile())
            return -1;
        if(o1.isFile() && o2.isDirectory())
                return 1;
        return o1.getName().compareTo(o2.getName());
        }
    });

    for(File f : files)
        System.out.println(f.getName());
     

    from: www.hilyb.com

  • 相关阅读:
    echarts仪表盘如何设置图例(legend)
    js上传限制文件大小
    js下载文件及命名(兼容多浏览器)
    为什么每个浏览器都有Mozilla字样(转载于知乎shadow)
    用JS做一个简单的电商产品放大镜功能
    unity下跨平台excel读写
    无限大地图:lightmap拆分
    Unity 打包总结和资源的优化和处理
    Unity3d: 资源释放时存储空间不足引发的思考和遇到的问题
    profiler内存优化:警惕回调函数
  • 原文地址:https://www.cnblogs.com/laiyubin/p/09c5cc279ccafb98c4ab4e16e0537b51.html
Copyright © 2011-2022 走看看