Java/File Input Output/FileFilter

Материал из 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);
      }
   }
}





A suffix based file 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.FileFilter;
/**
 * A <em>suffix</em> based file filter.
 * 
 * @version <tt>$Revision: 1958 $</tt>
 * @author 
 */
public class FileSuffixFilter implements FileFilter {
  /** A list of suffixes which files must have to be accepted. */
  protected final String suffixes[];
  /** Flag to signal that we want to ignore the case. */
  protected final boolean ignoreCase;
  /**
   * Construct a <tt>FileSuffixFilter</tt>.
   * 
   * @param suffixes
   *          A list of suffixes which files mut have to be accepted.
   * @param ignoreCase
   *          <tt>True</tt> if the filter should be case-insensitive.
   */
  public FileSuffixFilter(final String suffixes[], final boolean ignoreCase) {
    this.ignoreCase = ignoreCase;
    if (ignoreCase) {
      this.suffixes = new String[suffixes.length];
      for (int i = 0; i < suffixes.length; i++) {
        this.suffixes[i] = suffixes[i].toLowerCase();
      }
    } else {
      this.suffixes = suffixes;
    }
  }
  /**
   * Construct a <tt>FileSuffixFilter</tt>.
   * 
   * @param suffixes
   *          A list of suffixes which files mut have to be accepted.
   */
  public FileSuffixFilter(final String suffixes[]) {
    this(suffixes, false);
  }
  /**
   * Construct a <tt>FileSuffixFilter</tt>.
   * 
   * @param suffix
   *          The suffix which files must have to be accepted.
   * @param ignoreCase
   *          <tt>True</tt> if the filter should be case-insensitive.
   */
  public FileSuffixFilter(final String suffix, final boolean ignoreCase) {
    this(new String[] { suffix }, ignoreCase);
  }
  /**
   * Construct a case sensitive <tt>FileSuffixFilter</tt>.
   * 
   * @param suffix
   *          The suffix which files must have to be accepted.
   */
  public FileSuffixFilter(final String suffix) {
    this(suffix, false);
  }
  /**
   * Check if a file is acceptible.
   * 
   * @param file
   *          The file to check.
   * @return <tt>true</tt> if the file is acceptable.
   */
  public boolean accept(final File file) {
    boolean success = false;
    for (int i = 0; i < suffixes.length && !success; i++) {
      if (ignoreCase)
        success = file.getName().toLowerCase().endsWith(suffixes[i]);
      else
        success = file.getName().endsWith(suffixes[i]);
    }
    return success;
  }
}





Extension Filename Filter

    
/**
 * The utillib library.
 * More information is available at http://www.jinchess.ru/.
 * Copyright (C) 2002 Alexander Maryanovsky.
 * All rights reserved.
 *
 * The utillib 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 of the
 * License, or (at your option) any later version.
 *
 * The utillib 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 utillib library; 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;

/**
 * An implementation of the <code>java.io.FilenameFilter</code> which accepts
 * files whose name ends with a certain string. This makes it useful for
 * accepting files with a certain extension.
 */

public class ExtensionFilenameFilter implements FilenameFilter{

  /**
   * The strings with one of which a file"s name must end in order to pass the 
   * filter.
   */
  private final String [] endStrings;


  /**
   * Creates a new ExtensionFilenameFilter with the given string. Only files
   * ending with that string will be accepted. Note that in order to use this
   * class to accept only files with a certain extension, you must also provide
   * the "." character before the extension. For example, to accept only "txt"
   * files, you must pass ".txt".
   */
  public ExtensionFilenameFilter(String endString){
    this(new String[]{endString});
  }


  /**
   * Creates a new ExtensionFilenameFilter with the given string array. Only
   * files ending with one of the strings in the given string array will be
   * accepted by the created ExtensionFilenameFilter.  Note that in order to use
   * this class to accept only files with a certain extension, you must also 
   * provide the "." character before the extension. For example, to accept 
   * only "txt" files, you must pass ".txt".
   */
  public ExtensionFilenameFilter(String [] endStrings){
    this.endStrings = new String[endStrings.length];
    for (int i=0;i<endStrings.length;i++){
      this.endStrings[i] = endStrings[i];
    }
  }


  /**
   * Tests whether the specified file passes the filter. Returns true if the
   * file"s name ends with one of the string specified in the constructor.
   */
  public boolean accept(File dir, String filename){
    for (int i=0;i<endStrings.length;i++){
      if (filename.endsWith(endStrings[i]))
        return true;
    }
    return false;
  }

}





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 by file

   
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");
    FileFilter fileFilter = new FileFilter() {
      public boolean accept(File file) {
        return file.isDirectory();
      }
    };
    File[] files = dir.listFiles(fileFilter);
    
  }
}





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





Filters files based on the extension (what the filename ends with)

    
/****************************************************************
 * Licensed to the Apache Software Foundation (ASF) under one   *
 * or more contributor license agreements.  See the NOTICE file *
 * distributed with this work for additional information        *
 * regarding copyright ownership.  The ASF licenses this file   *
 * to you under the Apache License, Version 2.0 (the            *
 * "License"); you may not use this file except in compliance   *
 * with the License.  You may obtain a copy of the License at   *
 *                                                              *
 *   http://www.apache.org/licenses/LICENSE-2.0                 *
 *                                                              *
 * Unless required by applicable law or agreed to in writing,   *
 * software distributed under the License is distributed on an  *
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
 * KIND, either express or implied.  See the License for the    *
 * specific language governing permissions and limitations      *
 * under the License.                                           *
 ****************************************************************/
import java.io.File;
import java.io.FilenameFilter;
/**
 * This filters files based on the extension (what the filename
 * ends with). This is used in retrieving all the files of a
 * particular type.
 *
 * <p>Eg., to retrieve and print all <code>*.java</code> files in the current directory:</p>
 *
 * <pre>
 * File dir = new File(".");
 * String[] files = dir.list( new ExtensionFileFilter( new String[]{"java"} ) );
 * for (int i=0; i&lt;files.length; i++)
 * {
 *     System.out.println(files[i]);
 * }
 * </pre>
 *
 * @author  Federico Barbieri <fede@apache.org>
 * @author Serge Knystautas <sergek@lokitech.ru>
 * @author Peter Donald
 * @version CVS $Revision: 494012 $ $Date: 2007-01-08 11:23:58 +0100 (Mo, 08 Jan 2007) $
 * @since 4.0
 */
public class ExtensionFileFilter
    implements FilenameFilter
{
    private String[] m_extensions;
    public ExtensionFileFilter( final String[] extensions )
    {
        m_extensions = extensions;
    }
    public ExtensionFileFilter( final String extension )
    {
        m_extensions = new String[]{extension};
    }
    public boolean accept( final File file, final String name )
    {
        for( int i = 0; i < m_extensions.length; i++ )
        {
            if( name.endsWith( m_extensions[ i ] ) )
            {
                return true;
            }
        }
        return false;
    }
}





List files of a certain type

    
import java.io.File;
import java.io.FilenameFilter;
public class Main {
  public static void main(String[] args) {
    File directory = new File("c:\\");
    if (!directory.isDirectory()) {
      System.out.println("No directory provided");
      return;
    }
    FilenameFilter filefilter = new FilenameFilter() {
      public boolean accept(File dir, String name) {
        return name.endsWith(".txt");
      }
    };
    String[] filenames = directory.list(filefilter);
    for (String name : filenames) {
      System.out.println(name);
    }
  }
}