Example usage for java.io FileFilter accept

List of usage examples for java.io FileFilter accept

Introduction

In this page you can find the example usage for java.io FileFilter accept.

Prototype

boolean accept(File pathname);

Source Link

Document

Tests whether or not the specified abstract pathname should be included in a pathname list.

Usage

From source file:org.apache.asterix.test.base.AsterixTestHelper.java

public static void deepSelectiveCopy(File srcDir, File destDir, FileFilter filter) throws IOException {
    if (!srcDir.isDirectory()) {
        throw new IllegalArgumentException("Not a directory: " + srcDir);
    }/*w  w  w  .j a v  a2 s . c o  m*/
    if (destDir.exists() && !destDir.isDirectory()) {
        throw new IllegalArgumentException("Exists and not a directory: " + destDir);
    }
    for (File child : srcDir.listFiles()) {
        if (child.isDirectory()) {
            deepSelectiveCopy(child, new File(destDir, child.getName()), filter);
        } else if (filter.accept(child)) {
            destDir.mkdirs();
            FileUtils.copyFile(child, new File(destDir, child.getName()));
        }
    }
}

From source file:org.syncany.tests.unit.util.TestFileUtil.java

public static Map<String, File> getLocalFiles(File root, FileFilter filter) throws FileNotFoundException {
    List<File> fileList = getRecursiveFileList(root, true, false);
    Map<String, File> fileMap = new HashMap<String, File>();

    for (File file : fileList) {
        if (filter != null && !filter.accept(file)) {
            continue;
        }/*from  w  ww.j a v  a 2 s.  c o m*/

        String relativePath = FileUtil.getRelativePath(root, file);

        if (relativePath.startsWith(IGNORE_DIR_APPLICATION)) {
            continue;
        }

        fileMap.put(relativePath, file);
    }

    return fileMap;
}

From source file:fr.landel.utils.io.InternalFileSystemUtils.java

/**
 * Get if file matches the filter/*  w w  w.j  av  a  2 s. co m*/
 * 
 * @param file
 *            the file (required, if null returns false)
 * @param fileFilter
 *            the file filter (optional)
 * @param filenameFilter
 *            the filename filter (optional)
 * @return if filter matches
 */
protected static boolean matchFilter(final File file, final FileFilter fileFilter,
        final FilenameFilter filenameFilter) {
    boolean ok = false;
    if (file.isFile()) {
        if (fileFilter != null && fileFilter.accept(file)) {
            ok = true;
        } else if (filenameFilter != null && filenameFilter.accept(null, file.getName())) {
            ok = true;
        } else if (fileFilter == null && filenameFilter == null) {
            ok = true;
        }
    }
    return ok;
}

From source file:FileUtils.java

public static void copyDirectory(File source, File destination, FileFilter filter) throws IOException {
    File nextDirectory = new File(destination, source.getName());

    ///*from  www.  j  a  v a2  s. c  o  m*/
    // create the directory if necessary...
    //
    if (!nextDirectory.exists() && !nextDirectory.mkdirs()) {
        Object[] filler = { nextDirectory.getAbsolutePath() };
        String message = "DirCopyFailed";
        throw new IOException(message);
    }

    File[] files = source.listFiles();

    //
    // and then all the items below the directory...
    //
    for (int n = 0; n < files.length; ++n) {
        if (filter == null || filter.accept(files[n])) {
            if (files[n].isDirectory())
                copyDirectory(files[n], nextDirectory, filter);

            else
                copyFile(files[n], nextDirectory);
        }
    }
}

From source file:gedi.util.FileUtils.java

/**
 * Finds files starting from root using filter and puts them into list.
 * @param root the root to start//from ww w.j  a  v a2s .com
 * @param filter the file filter
 * @param list the result list
 */
public static void findFiles(File root, FileFilter filter, List<File> list, boolean recursive) {
    for (File f : root.listFiles())
        if (filter.accept(f))
            list.add(f);
        else if (recursive && f.isDirectory())
            findFiles(f, filter, list, recursive);
}

From source file:bb.io.TarUtil.java

/**
* Writes path as a new TarArchiveEntry to tarArchiveOutputStream.
* If path is a normal file, then next writes path's data to tarArchiveOutputStream.
* <p>//from  w ww  .j  av  a  2s.c o  m
* If path is a directory, then this method additionally calls itself on the contents
* (thus recursing thru the entire directory tree).
* <p>
* <b>Warning</b>: several popular programs (e.g. winzip) fail to display mere directory entries.
* Furthermore, if just a directory entry is present (i.e. it is empty), they also may fail
* to create a new empty directoy when extracting the TAR file's contents.
* These are bugs in their behavior.
* <p>
* An optional FileFilter can be supplied to screen out paths that would otherwise be archived.
* <p>
* <i>This method does not close tarArchiveOutputStream:</i> that is the responsibility of the caller.
* <p>
* The caller also must take on the responsibility to not do anything stupid, like write
* path more than once, or have the path be the same File that tarArchiveOutputStream is writing to.
* <p>
* @param path the File to archive
* @param fileParent the FileParent for path
* @param tarArchiveOutputStream the TarArchiveOutputStream that will write the archive data to
* @param filter a FileFilter that can use to screen out certain files from being written to the archive; may be null (so everything specified by path gets archived)
* @throws Exception if any Throwable is caught; the Throwable is stored as the cause, and the message stores path's information;
* here are some of the possible causes:
* <ol>
*  <li>IllegalArgumentException if path fails {@link #isTarable isTarable}</li>
*  <li>SecurityException if a security manager exists and its SecurityManager.checkRead method denies read access to path</li>
*  <li>IOException if an I/O problem occurs</li>
* </ol>
*/
private static void archive(File path, FileParent fileParent, TarArchiveOutputStream tarArchiveOutputStream,
        FileFilter filter) throws Exception {
    try {
        if ((filter != null) && !filter.accept(path))
            return;
        if (!isTarable(path))
            throw new IllegalArgumentException("path = " + path.getPath() + " failed isTarable");
        if (giveUserFeedback)
            ConsoleUtil.overwriteLine("TarUtil.archive: " + path.getPath());

        TarArchiveEntry entry = new TarArchiveEntry(path);
        entry.setName(fileParent.getRelativePath(path, '/')); // Note: getRelativePath will ensure that '/' is the path separator and that directories end with '/'
        tarArchiveOutputStream.putNextEntry(entry);
        if (path.isFile())
            readInFile(path, tarArchiveOutputStream);
        tarArchiveOutputStream.closeEntry();

        if (path.isDirectory()) {
            for (File fileChild : DirUtil.getContents(path, null)) { // supply null, since we test at beginning of this method (supplying filter here will just add a redundant test)
                archive(fileChild, fileParent, tarArchiveOutputStream, filter);
            }
        }
    } catch (Throwable t) {
        String preface = "See cause for the underlying Throwable; happened for path = ";
        if ((t instanceof Exception) && (t.getMessage().startsWith(preface)))
            throw (Exception) t; // CRITICAL: see if t was actually the wrapping Exception generated by a subsequent recursive call to this method, and if so simply rethrow it unmodified to avoid excessive exception chaining
        throw new Exception(preface + (path != null ? path.getPath() : "<null>"), t);
    }
}

From source file:com.google.dart.tools.update.core.internal.UpdateUtils.java

/**
 * Copy the contents of one directory to another directory recursively.
 * //from ww w .j  a v  a  2s.  c om
 * @param fromDir the source
 * @param toDir the target
 * @param overwriteFilter a filter to determine if a given file should be overwritten in a copy
 * @param monitor a monitor for providing progress feedback
 * @throws IOException
 */
public static void copyDirectory(File fromDir, File toDir, FileFilter overwriteFilter, IProgressMonitor monitor)
        throws IOException {
    for (File f : fromDir.listFiles()) {
        File toFile = new File(toDir, f.getName());
        if (f.isFile()) {
            if (!toFile.exists() || overwriteFilter.accept(toFile)) {
                copyFile(f, toFile, monitor);
            }
        } else {
            if (!toFile.isDirectory()) {
                toFile.delete();
            }
            if (!toFile.exists()) {
                toFile.mkdir();
            }

            copyDirectory(f, toFile, overwriteFilter, monitor);
        }
    }

}

From source file:org.jahia.utils.FileUtils.java

/**
 * Cleans a directory without deleting it, considering also named exclusions.
 *
 * @param directory directory to clean//from   w  w  w .j  a v a  2s  .com
 * @param filter the file filter to consider 
 * @throws IOException in case cleaning is unsuccessful
 * @see org.apache.commons.io.FileUtils#cleanDirectory(File)
 */
public static void cleanDirectory(File directory, FileFilter filter) throws IOException {
    if (!directory.exists()) {
        String message = directory + " does not exist";
        throw new IllegalArgumentException(message);
    }

    if (!directory.isDirectory()) {
        String message = directory + " is not a directory";
        throw new IllegalArgumentException(message);
    }

    File[] files = directory.listFiles();
    if (files == null) { // null if security restricted
        throw new IOException("Failed to list contents of " + directory);
    }

    if (files.length == 0) {
        return;
    }

    IOException exception = null;
    for (File file : files) {
        if (filter != null && !filter.accept(file)) {
            continue;
        }
        try {
            org.apache.commons.io.FileUtils.forceDelete(file);
        } catch (IOException ioe) {
            exception = ioe;
        }
    }

    if (null != exception) {
        throw exception;
    }
}

From source file:com.norconex.commons.lang.file.FileUtil.java

/**
 * Visits all files (and only files) under a directory, including 
 * sub-directories./*  w ww. j  a  va2 s.com*/
 * @param dir the directory
 * @param visitor the visitor
 * @param filter an optional filter to restrict the files being visited 
 */
public static void visitAllFiles(File dir, IFileVisitor visitor, FileFilter filter) {
    if (!dir.exists()) {
        return;
    } else if (dir.isDirectory()) {
        String[] children = dir.list();
        if (children != null) {
            for (int i = 0; i < children.length; i++) {
                visitAllFiles(new File(dir, children[i]), visitor, filter);
            }
        }
    } else if (filter == null || filter.accept(dir)) {
        visitor.visit(dir);
    }
}

From source file:net.sf.zekr.ui.MessageBoxUtils.java

/**
 * This method opens a file chooser dialog and selects file filtering with the given wildcards.
 * //from  w  w w . j av  a  2 s  .c  o  m
 * @param parentShall
 * @param filterNames names of the filters
 * @param filterWildcards wildcard filters (e.g. *.zip)
 * @param multi indicates whether this open dialog can select multiple or single items
 * @return a 0-item list if action canceled, no item was selected or selected items did not fit the
 *         extension criteria. Otherwise, returns a list of selected files (of type <tt>java.io.File</tt>).
 * @throws IOException if any exception occurred during importing.
 */
public static List<File> importFileDialog(Shell parentShall, String[] filterNames, String[] filterWildcards,
        boolean multi) throws IOException {
    FileDialog fd = new FileDialog(parentShall, SWT.OPEN | (multi ? SWT.MULTI : SWT.SINGLE));
    // fd.setFilterPath(GlobalConfig.getDefaultStartFolder()); // this code is a real pain!
    fd.setFilterNames(filterNames);
    fd.setFilterExtensions(filterWildcards); // Windows wild card
    fd.setText(lang.getMeaning("OPEN"));

    FileFilter fileFilter = new WildcardFileFilter(filterWildcards[0].split(";"));
    //this needs to be like this due to a mismatch between the WildcardFileFilter concept
    //of multi-extension wild card and the one use in the file dialog.

    List<File> fileList = new ArrayList<File>();

    String res = fd.open();
    if (res == null)
        return fileList;

    String fileNames[] = fd.getFileNames();
    for (int i = 0; i < fileNames.length; i++) {
        File srcFile = new File(fd.getFilterPath(), fileNames[i]);
        if (fileFilter.accept(srcFile)) {
            if (!srcFile.exists()) {
                logger.warn("File not found: " + srcFile);
                MessageBoxUtils.showError(lang.getMeaning("FNF") + ":\n" + srcFile);
                return new ArrayList<File>();
            }
            fileList.add(srcFile);
        }
    }
    logger.debug("Files chosen: " + fileList);
    return fileList;
}