Java/File Input Output/FilenameFilter

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

Accepts a selection if it is acceptable to both of two FilenameFilters

   <source lang="java">
  

import java.io.File; import java.io.FilenameFilter; /**

* Accepts a selection if it is acceptable to both of two {@link FilenameFilter}s.
* This takes two {@link FilenameFilter}s as input.
*
*

Eg., to print all files beginning with A and ending with .java:

*
*
 * File dir = new File(".");
 * String[] files = dir.list( new AndFileFilter(
 *         new PrefixFileFilter("A"),
 *         new ExtensionFileFilter(".java")
 *         )
 *     );
 * 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 AndFileFilter

   implements FilenameFilter

{

   private final FilenameFilter m_filter1;
   private final FilenameFilter m_filter2;
   public AndFileFilter( final FilenameFilter filter1, final FilenameFilter filter2 )
   {
       m_filter1 = filter1;
       m_filter2 = filter2;
   }
   public boolean accept( final File file, final String name )
   {
       return m_filter1.accept( file, name ) && m_filter2.accept( file, name );
   }

}


 </source>
   
  
 
  



A simple file filter for a particular file extension

   <source lang="java">
  

//revised from prefuse import java.io.File; import java.util.ArrayList; import java.util.Iterator; import javax.swing.filechooser.FileFilter; /**

* A simple file filter for a particular file extension.
*  
* @author 
*/

public class SimpleFileFilter extends FileFilter {

   private ArrayList exts = new ArrayList();
   private String desc;
   private Object data;
   
   /**
    * Create a new SimpleFileFilter.
    * @param ext the file extension
    * @param desc a description of the file type
    */
   public SimpleFileFilter(String ext, String desc) {
       addExtension(ext);
       this.desc = desc;
   }
   
   /**
    * Create a new SimpleFileFilter.
    * @param ext the file extension
    * @param desc a description of the file type
    * @param data user-provided attached object
    */
   public SimpleFileFilter(String ext, String desc, Object data) {
       addExtension(ext);
       this.desc = desc;
       this.data = data;
   }
   
   /**
    * Add a file extension to this file filter.
    * @param ext the file extension to add
    */
   public void addExtension(String ext) {
       exts.add(ext.toLowerCase());
   }
   
   /**
    * @see javax.swing.filechooser.FileFilter#accept(java.io.File)
    */
   public boolean accept(File f) {
       if ( f == null )
           return false;
       if ( f.isDirectory() )
           return true;
       String extension = getExtension(f);
       if ( extension == null ) return false;
       for ( Iterator iter = exts.iterator(); iter.hasNext(); ) {
           String ext = (String)iter.next();
           if ( ext.equalsIgnoreCase(extension) )
               return true;
       }
       return false;
   }
   /**
    * Returns the extension for a file or null if there is none
    * @param f the input file
    * @return the file extension, or null if none
    */
   public static String getExtension(File f) {
       return (f != null ? getExtension(f.getName()) : null);
   }
   /**
    * Returns the extension for a file or null if there is none
    * @param filename the input filename
    * @return the file extension, or null if none
    */
   public static String getExtension(String filename) {
       int i = filename.lastIndexOf(".");
       if ( i>0 && i<filename.length()-1 ) {
           return filename.substring(i+1).toLowerCase();
       } else {
           return null;
       }
   }
   /**
    * Get a user-provided attached object.
    * @return the user-provided attached object
    */
   public Object getUserData() {
       return data;
   }
   
   /**
    * @see javax.swing.filechooser.FileFilter#getDescription()
    */
   public String getDescription() {
       return desc;
   }
   
   /**
    * Get the first file extension associated with this filter.
    * @return the first file extension associated with this filter
    */
   public String getExtension() {
       return (String)exts.get(0);
   }
   

} // end of class SimpleFileFilter


 </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>
   
  
 
  



only display files that use the .html extension.

   <source lang="java">
  

import java.io.File; import java.io.FilenameFilter; class DirListOnly {

 public static void main(String args[]) {
   String dirname = "/java";
   File f1 = new File(dirname);
   FilenameFilter only = new OnlyExt("html");
   String s[] = f1.list(only);
   for (int i = 0; i < s.length; i++) {
     System.out.println(s[i]);
   }
 }

} class OnlyExt implements FilenameFilter {

 String ext;
 public OnlyExt(String ext) {
   this.ext = "." + ext;
 }
 public boolean accept(File dir, String name) {
   return name.endsWith(ext);
 }

}


 </source>
   
  
 
  



Removes the file extension from the given file name.

   <source lang="java">
 

import java.net.URL; /*

* 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.]
* 
* ------------
* IOUtils.java
* ------------
* (C)opyright 2002-2004, by Thomas Morgner and Contributors.
*
* Original Author:  Thomas Morgner;
* Contributor(s):   David Gilbert (for Object Refinery Limited);
*
* $Id: IOUtils.java,v 1.8 2009/01/22 08:34:58 taqua Exp $
*
* Changes
* -------
* 26-Jan-2003 : Initial version
* 23-Feb-2003 : Documentation
* 25-Feb-2003 : Fixed Checkstyle issues (DG);
* 29-Apr-2003 : Moved to jcommon
* 04-Jan-2004 : Fixed JDK 1.2.2 issues with createRelativeURL;
*               added support for query strings within these urls (TM);
*/

/**

* The IOUtils provide some IO related helper methods.
*
* @author Thomas Morgner.
*/

public class Main {

 /**
  * Removes the file extension from the given file name.
  *
  * @param file the file name.
  * @return the file name without the file extension.
  */
 public String stripFileExtension(final String file) {
     final int idx = file.lastIndexOf(".");
     // handles unix hidden files and files without an extension.
     if (idx < 1) {
         return file;
     }
     return file.substring(0, idx);
 }

}


 </source>
   
  
 
  



Returns the file extension of the given file name. The returned value will contain the dot.

   <source lang="java">
 

import java.net.URL; /*

* 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.]
* 
* ------------
* IOUtils.java
* ------------
* (C)opyright 2002-2004, by Thomas Morgner and Contributors.
*
* Original Author:  Thomas Morgner;
* Contributor(s):   David Gilbert (for Object Refinery Limited);
*
* $Id: IOUtils.java,v 1.8 2009/01/22 08:34:58 taqua Exp $
*
* Changes
* -------
* 26-Jan-2003 : Initial version
* 23-Feb-2003 : Documentation
* 25-Feb-2003 : Fixed Checkstyle issues (DG);
* 29-Apr-2003 : Moved to jcommon
* 04-Jan-2004 : Fixed JDK 1.2.2 issues with createRelativeURL;
*               added support for query strings within these urls (TM);
*/

/**

* The IOUtils provide some IO related helper methods.
*
* @author Thomas Morgner.
*/

public class Main {

 /**
  * Returns the file extension of the given file name.
  * The returned value will contain the dot.
  *
  * @param file the file name.
  * @return the file extension.
  */
 public String getFileExtension(final String file) {
     final int idx = file.lastIndexOf(".");
     // handles unix hidden files and files without an extension.
     if (idx < 1) {
         return "";
     }
     return file.substring(idx);
 }

}


 </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>