Java Tutorial/File/FileFilter

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

A suffix based file filter.

   <source lang="java">

/*

* 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 suffix based file filter.
* 
* @version $Revision: 1958 $
* @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 FileSuffixFilter.
  * 
  * @param suffixes
  *          A list of suffixes which files mut have to be accepted.
  * @param ignoreCase
  *          True 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 FileSuffixFilter.
  * 
  * @param suffixes
  *          A list of suffixes which files mut have to be accepted.
  */
 public FileSuffixFilter(final String suffixes[]) {
   this(suffixes, false);
 }
 /**
  * Construct a FileSuffixFilter.
  * 
  * @param suffix
  *          The suffix which files must have to be accepted.
  * @param ignoreCase
  *          True if the filter should be case-insensitive.
  */
 public FileSuffixFilter(final String suffix, final boolean ignoreCase) {
   this(new String[] { suffix }, ignoreCase);
 }
 /**
  * Construct a case sensitive FileSuffixFilter.
  * 
  * @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 true 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;
 }

}</source>





Create custom File filter

   <source lang="java">

import java.io.File; import java.io.FileFilter; public class MainClass {

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

}</source>





Custom File Filter

   <source lang="java">

import java.io.File; import java.util.Enumeration; import java.util.Hashtable; import javax.swing.filechooser.FileFilter; public class CustomFileFilter extends FileFilter {

 private Hashtable filters = null;
 private String description = null;
 private String fullDescription = null;
 private boolean useExtensionsInDescription = true;
 public CustomFileFilter() {
   this.filters = new Hashtable();
 }
 public CustomFileFilter(String extension) {
   this(extension, null);
 }
 public CustomFileFilter(String extension, String description) {
   this();
   if (extension != null)
     addExtension(extension);
   if (description != null)
     setDescription(description);
 }
 public CustomFileFilter(String[] filters) {
   this(filters, null);
 }
 public CustomFileFilter(String[] filters, String description) {
   this();
   for (int i = 0; i < filters.length; i++) {
     addExtension(filters[i]);
   }
   if (description != null)
     setDescription(description);
 }
 public boolean accept(File f) {
   if (f != null) {
     if (f.isDirectory()) {
       return true;
     }
     String extension = getExtension(f);
     if (extension != null && filters.get(getExtension(f)) != null) {
       return true;
     }
   }
   return false;
 }
 public String getExtension(File f) {
   if (f != null) {
     String filename = f.getName();
     int i = filename.lastIndexOf(".");
     if (i > 0 && i < filename.length() - 1) {
       return filename.substring(i + 1).toLowerCase();
     }
   }
   return null;
 }
 public void addExtension(String extension) {
   if (filters == null) {
     filters = new Hashtable(5);
   }
   filters.put(extension.toLowerCase(), this);
   fullDescription = null;
 }
 public String getDescription() {
   if (fullDescription == null) {
     if (description == null || isExtensionListInDescription()) {
       fullDescription = description == null ? "(" : description + " (";
       Enumeration extensions = filters.keys();
       if (extensions != null) {
         fullDescription += "." + (String) extensions.nextElement();
         while (extensions.hasMoreElements()) {
           fullDescription += ", " + (String) extensions.nextElement();
         }
       }
       fullDescription += ")";
     } else {
       fullDescription = description;
     }
   }
   return fullDescription;
 }
 public void setDescription(String description) {
   this.description = description;
   fullDescription = null;
 }
 public void setExtensionListInDescription(boolean b) {
   useExtensionsInDescription = b;
   fullDescription = null;
 }
 public boolean isExtensionListInDescription() {
   return useExtensionsInDescription;
 }

}</source>





Files filter that filters files by their suffix (or extension)

   <source lang="java">

/*

* $Id: SuffixFilenameFilter.java,v 1.1.1.1 2005/04/07 18:36:22 pocho Exp $
*/

import java.io.File; import java.io.FilenameFilter; import javax.swing.filechooser.FileFilter; /**

* Files filter that filters files by their suffix (or extension).
* It can be used as file filter for {@link javax.swing.JFileChooser} or
* as file filter for io operations (@link java.io.File#listFiles(java.io.FilenameFilter)}.
* 
* @version $Name:  $ - $Revision: 1.1.1.1 $ - $Date: 2005/04/07 18:36:22 $
* TODO Test
*/

public class SuffixFilenameFilter extends FileFilter implements FilenameFilter {

 /** Suffix of files */
 private String suffix;
 
 /** Description of suffix (i.e. .jpg may have description JPG)*/
 private String description;
 
 /** Full description of filter - (i.e. JPG (.jpg) */
 private String fullDescription;
 
 /** Indicates whether to use suffix in brackets after description */
 private boolean useExtensionInDescription = true;
 /**
  * Creates new instance with a given accepted suffix of file names.
  *
  * @param suffix used suffix of files (i.e. extension ".xml")
  */
 public SuffixFilenameFilter(String suffix) {
   this(suffix, null);
 }
 /**
  * Creates new instance with a given accepted suffix of file names.
  *
  * @param suffix used suffix of files (i.e. extension ".xml")
  */
 public SuffixFilenameFilter(String suffix, String description) {
   super();
   setSuffix(suffix);
   setDescription(description);
 }
 /**
  * Indicates whether the name is accepted by this filter or not.
  * File must ending with given mask of this filter.
  *
  * @param dir File
  * @param name String
  * @return boolean
  */
 public boolean accept(File dir, String name){
 if (name.lastIndexOf(suffix) > 0)
     return true;
   else
     return false;
 }
 public boolean accept(File file) {
   if (file != null) {
     if (file.isDirectory() || accept(file.getParentFile(), file.getName()))
         return true;
   }
   return false;
 }
 /**
  * Returns description of this filter - if {@link #isExtensionInDescription()}
  * is true then it creates description in following shape:
* description (suffix). Otherwise it only returns description. * * @see javax.swing.filechooser.FileFilter#getDescription() */ public String getDescription() { if (fullDescription == null && isExtensionInDescription()) { fullDescription = description==null ? "(" : description + " ("; fullDescription += suffix + ")"; } return fullDescription; } /** * Sets whether to use suffix in description of this filter. * * @param b */ public void setExtensionInDescription(boolean b) { useExtensionInDescription = b; fullDescription = null; } public boolean isExtensionInDescription() { return useExtensionInDescription; } public void setSuffix(String suffix) { this.suffix = suffix; fullDescription = null; } public void setDescription(String description) { this.description = description; fullDescription = null; } public String getExtension() { return suffix; } public String getSimpleDescription() { return description; }

}</source>





Filter by file

   <source lang="java">

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

}</source>





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

   <source lang="java">

/****************************************************************

* 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.
*
* Eg., to retrieve and print all *.java files in the current directory:
*
*
 * File dir = new File(".");
 * String[] files = dir.list( new ExtensionFileFilter( new String[]{"java"} ) );
 * for (int i=0; i<files.length; i++)
 * {
 *     System.out.println(files[i]);
 * }
 * 
*
* @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;
   }

}</source>





Generic File Filter

   <source lang="java">

import java.io.File; import javax.swing.filechooser.FileFilter; public class GenericFileFilter extends FileFilter {

 private String[] fileExts;
 private String description;
 private String extension;
 public GenericFileFilter(String[] filesExtsIn, String description) {
   fileExts = filesExtsIn;
   this.description = description;
 }
 public boolean accept(File f) {
   if (f.isDirectory()) {
     return true;
   }
   extension = getExtension(f);
   if (extension != null) {
     for (int i = 0; i < fileExts.length; i++) {
       if (check(fileExts[i]))
         return true;
     }
   }
   return false;
 }
 private boolean check(String in) {
   return extension.equalsIgnoreCase(in);
 }
 public String getDescription() {
   return description;
 }
 private String getExtension(File file) {
   String filename = file.getName();
   int length = filename.length();
   int i = filename.lastIndexOf(".");
   if (i > 0 && i < length - 1)
     return filename.substring(i + 1).toLowerCase();
   return null;
 }

}</source>





Inverted File Filter

   <source lang="java">

/****************************************************************

* 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 takes a FilenameFilter<code> as input and inverts the selection.
* This is used in retrieving files that are not accepted by a filter.
*
* @author 
* @version CVS $Revision: 494012 $ $Date: 2007-01-08 11:23:58 +0100 (Mo, 08 Jan 2007) $
* @since 4.0
*/

public class InvertedFileFilter

   implements FilenameFilter

{

   private final FilenameFilter m_originalFilter;
   public InvertedFileFilter( final FilenameFilter originalFilter )
   {
       m_originalFilter = originalFilter;
   }
   public boolean accept( final File file, final String name )
   {
       return !m_originalFilter.accept( file, name );
   }

}</source>





List file with file filter

   <source lang="java">

import java.io.File; import java.io.FileFilter; public class MainClass {

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

}</source>





This filter accepts Files that are directories

   <source lang="java">

/****************************************************************

* 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 filter accepts <code>Files that are directories.
* Eg., here is how to print out a list of the current directory"s subdirectories:
*
*
 * File dir = new File(".");
 * String[] files = dir.list( new DirectoryFileFilter() );
 * for ( int i=0; i<files.length; i++ )
 * {
 *     System.out.println(files[i]);
 * }
 * 
*
* @author 
* @version $Revision: 494012 $ $Date: 2007-01-08 11:23:58 +0100 (Mo, 08 Jan 2007) $
* @since 4.0
*/

public class DirectoryFileFilter

   implements FilenameFilter

{

   public boolean accept( final File file, final String name )
   {
       return new File( file, name ).isDirectory();
   }

}</source>