Java Tutorial/File/FilenameFilter

Материал из Java эксперт
Перейти к: навигация, поиск

A filesystem filter.

/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ------------------------
 * ExtensionFileFilter.java
 * ------------------------
 * (C) Copyright 2000-2004, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   -;
 *
 * $Id: FilesystemFilter.java,v 1.6 2008/09/10 09:26:11 mungady Exp $
 *
 * Changes (from 26-Oct-2001)
 * --------------------------
 * 01-Jun-2005 : Updated javadoc.
 */
import java.io.File;
import java.io.FilenameFilter;
import javax.swing.filechooser.FileFilter;
/**
 * A filesystem filter.
 * 
 * @author David Gilbert
 */
public class FilesystemFilter extends FileFilter implements FilenameFilter {
  /** The file extension, which should be accepted. */
  private String[] fileext;
  /** The filter description. */
  private String descr;
  /** A flag indicating whether to accept directories. */
  private boolean accDirs;
  /**
   * Creates a new filter.
   * 
   * @param fileext
   *          the file extension.
   * @param descr
   *          the description.
   */
  public FilesystemFilter(final String fileext, final String descr) {
    this(fileext, descr, true);
  }
  /**
   * Creates a new filter.
   * 
   * @param fileext
   *          the file extension.
   * @param descr
   *          the description.
   * @param accDirs
   *          accept directories?
   */
  public FilesystemFilter(final String fileext, final String descr, final boolean accDirs) {
    this(new String[] { fileext }, descr, accDirs);
  }
  /**
   * Creates a new filter.
   * 
   * @param fileext
   *          the file extension.
   * @param descr
   *          the description.
   * @param accDirs
   *          accept directories?
   * @throws NullPointerException
   *           if the file extensions are null.
   */
  public FilesystemFilter(final String[] fileext, final String descr, final boolean accDirs) {
    this.fileext = (String[]) fileext.clone();
    this.descr = descr;
    this.accDirs = accDirs;
  }
  /**
   * Returns <code>true</code> if the file is accepted, and <code>false</code>
   * otherwise.
   * 
   * @param dir
   *          the directory.
   * @param name
   *          the file name.
   * @return A boolean.
   */
  public boolean accept(final File dir, final String name) {
    final File f = new File(dir, name);
    if (f.isDirectory() && acceptsDirectories()) {
      return true;
    }
    for (int i = 0; i < this.fileext.length; i++) {
      if (name.endsWith(this.fileext[i])) {
        return true;
      }
    }
    return false;
  }
  /**
   * Returns <code>true</code> if the specified file matches the requirements
   * of this filter, and <code>false</code> otherwise.
   * 
   * @param dir
   *          the file or directory.
   * @return A boolean.
   */
  public boolean accept(final File dir) {
    if (dir.isDirectory() && acceptsDirectories()) {
      return true;
    }
    for (int i = 0; i < this.fileext.length; i++) {
      if (dir.getName().endsWith(this.fileext[i])) {
        return true;
      }
    }
    return false;
  }
  /**
   * Returns the filter description.
   * 
   * @return The filter description.
   */
  public String getDescription() {
    return this.descr;
  }
  /**
   * Sets the flag that controls whether or not the filter accepts directories.
   * 
   * @param b
   *          a boolean.
   */
  public void acceptDirectories(final boolean b) {
    this.accDirs = b;
  }
  /**
   * Returns the flag that indicates whether or not the filter accepts
   * directories.
   * 
   * @return A boolean.
   */
  public boolean acceptsDirectories() {
    return this.accDirs;
  }
}





A prefix based filename filter

/*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
import java.io.File;
import java.io.FilenameFilter;
/**
 * A <em>prefix</em> based filename filter.
 *
 * @version <tt>$Revision: 1958 $</tt>
 * @author  
 */
public class FilenamePrefixFilter
   implements FilenameFilter
{
   /** The prefix which files must have to be accepted. */
   protected final String prefix;
   /** Flag to signal that we want to ignore the case. */
   protected final boolean ignoreCase;
   /**
    * Construct a <tt>FilenamePrefixFilter</tt>.
    *
    * @param prefix     The prefix which files must have to be accepted.
    * @param ignoreCase <tt>True</tt> if the filter should be case-insensitive.
    */
   public FilenamePrefixFilter(final String prefix,
                               final boolean ignoreCase)
   {
      this.ignoreCase = ignoreCase;
      this.prefix = (ignoreCase ? prefix.toLowerCase() : prefix);
   }
   /**
    * Construct a case sensitive <tt>FilenamePrefixFilter</tt>.
    *
    * @param prefix  The prefix which files must have to be accepted.
    */
   public FilenamePrefixFilter(final String prefix) {
      this(prefix, false);
   }
   /**
    * Check if a file is acceptible.
    *
    * @param dir  The directory the file resides in.
    * @param name The name of the file.
    * @return     <tt>true</tt> if the file is acceptable.
    */
   public boolean accept(final File dir, final String name) {
      if (ignoreCase) {
         return name.toLowerCase().startsWith(prefix);
      }
      else {
         return name.startsWith(prefix);
      }
   }
}





Combine FilenameFilter and Pattern match to create a dir command

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.regex.Pattern;
public class MainClass {
  public static void main(final String[] args) {
    File path = new File(".");
    String[] list;
    if (args.length == 0)
      list = path.list();
    else
      list = path.list(new FilenameFilter() {
        private Pattern pattern = Pattern.rupile(args[0]);
        public boolean accept(File dir, String name) {
          return pattern.matcher(new File(name).getName()).matches();
        }
      });
    Arrays.sort(list);
    for (int i = 0; i < list.length; i++)
      System.out.println(list[i]);
  }
}





File filter: retrieve at most predefined number of files which are older than specified data

/*
 * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
 * 
 * Project: OpenSubsystems
 * 
 * $Id: MaximumFileFilter.java,v 1.4 2007/01/07 06:14:00 bastafidli Exp $
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License. 
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
 */

import java.io.File;
import java.io.FilenameFilter;
import java.util.Date;
/**
 * File filter implementation to retrieve at most predefined number of files
 * which are older than specified data
 * 
 * @version $Id: MaximumFileFilter.java,v 1.4 2007/01/07 06:14:00 bastafidli Exp $
 * @author Miro Halas
 * @code.reviewer Miro Halas
 * @code.reviewed 1.2 2004/12/18 06:18:25 bastafidli
 */
public class MaximumFileFilter implements FilenameFilter
{
   // Attributes ///////////////////////////////////////////////////////////////
   
   /**
    * Current number of files in list
    */
   protected int m_currentFileCount = 0;
   
   /**
    * Maximum number of files in output list
    */
   
   protected int m_iMaximum = 0;
   
   /**
    * Last modification time of file have to be before this date, if it is null, 
    * modification date is not checked
    */
   protected Date m_dtOlderThan;
   
   // Constructors /////////////////////////////////////////////////////////////
   
   /**
    * Constructor with maximum count of file in the output list.
    *  
    * @param iMax - maximum number of files in output list. If it is 0 length of 
    * @param dtOlderThen  - file last modification time heve to by before this 
    *                       date, if it is null modification time is not checked
    *                       output list is unlimited.
    */
   
   public MaximumFileFilter(
      int  iMax,
      Date dtOlderThen
   )
   {
      m_iMaximum = iMax;
      m_dtOlderThan = dtOlderThen; 
   }
   
   /**
    * {@inheritDoc}
    */
   public boolean accept(
      File   dir, 
      String name
   )
   {
      File currentFile = new File(dir, name);
      
      if (currentFile.isDirectory())
      {
         return false;
      }
      if ((m_dtOlderThan != null) && (currentFile.lastModified() > m_dtOlderThan.getTime()))
      {
         return false;
      }
      if ((m_iMaximum == 0) || (m_currentFileCount <= m_iMaximum))
      {
         m_currentFileCount++;
      }
      return  m_currentFileCount <= m_iMaximum;
   }
}





Filter files by name

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
public class Main {
  public static void main(String[] argv) throws Exception {
    File dir = new File("c:\\temp");
    FilenameFilter filter = new FilenameFilter() {
      public boolean accept(File dir, String name) {
        return !name.startsWith(".");
      }
    };
    String[] children = dir.list(filter);
    
  }
}





strip Extension name

import java.io.File;

public class Main {
  

  /**
   * org/my/Class.xxx -> org/my/Class
   */
  public static String stripExtension( final String pResourceName ) {
      final int i = pResourceName.lastIndexOf(".");
      if (i < 0) {
          return pResourceName;
      }
      final String withoutExtension = pResourceName.substring(0, i);
      return withoutExtension;
  }
}