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.openflexo.toolbox.FileUtils.java

public static void copyContentDirToDir(File src, File dest, CopyStrategy strategy, FileFilter fileFilter)
        throws IOException {
    if (!src.exists()) {
        return;//from w  ww .  ja va  2s .com
    }
    if (!dest.exists()) {
        dest.mkdirs();
    }
    File[] fileArray = src.listFiles();
    for (int i = 0; i < fileArray.length; i++) {
        File curFile = fileArray[i];
        if (curFile.isDirectory() && !curFile.getName().equals("CVS") && fileFilter.accept(curFile)) {
            copyContentDirToDir(curFile, new File(dest, curFile.getName()), strategy, fileFilter);
        } else if (curFile.isFile() && fileFilter.accept(curFile)) {
            File destFile = new File(dest, curFile.getName());
            if (destFile.exists()) {
                switch (strategy) {
                case IGNORE_EXISTING:
                    continue;
                case REPLACE_OLD_ONLY:
                    if (!getDiskLastModifiedDate(src).after(getDiskLastModifiedDate(destFile))) {
                        continue;
                    }
                default:
                    break;
                }
            }
            copyFileToFile(curFile, destFile);
        }
    }
}

From source file:org.qedeq.base.io.IoUtility.java

/**
 * List all matching files. Searches all matching sub directories recursively.
 * Remember to return <code>true</code> for <code>accept(File pathname)</code> if
 * <code>pathname</code> is a directory if you want to search all sub directories!
 *
 * @param   sourceLocation  Check all files in this directory.
 * @param   filter          Accept only these directories and files.
 * @return  List of matching files. Contains no directories.
 * @throws  IOException     Something went wrong.
 *//*from w  w w .  j ava  2  s. co m*/
private static List listFilesRecursivelyIntern(final File sourceLocation, final FileFilter filter)
        throws IOException {
    final List result = new ArrayList();
    if (filter.accept(sourceLocation)) {
        if (sourceLocation.isDirectory()) {
            File[] children = sourceLocation.listFiles();
            for (int i = 0; i < children.length; i++) { // recursive call for all children
                result.addAll(listFilesRecursivelyIntern(children[i], filter));
            }
        } else {
            result.add(sourceLocation);
        }
    }
    return result;
}

From source file:org.olat.core.util.FileUtils.java

/**
 * Copy a directory from one spot on hard disk to another. Will create any target dirs if necessary.
 * //  ww w  .  j  a va2 s .  c  o  m
 * @param sourceDir directory to copy on local hard disk.
 * @param targetDir new directory to be created on local hard disk.
 * @param move
 * @param createDir If true, a directory with the name of the source directory will be created
 * @param filter file filter or NULL if no filter applied
 * @return true if the copy was successful.
 */
private static boolean copyDirInternal(File sourceDir, File targetDir, boolean move, boolean createDir,
        FileFilter filter, String wt) {
    if (sourceDir.isFile())
        return copyFileToDir(sourceDir, targetDir, move, filter, wt);
    if (!sourceDir.isDirectory())
        return false;

    // copy only if filter allows. filtered items are considered a success
    // and not a failure of the operation
    if (filter != null && !filter.accept(sourceDir))
        return true;

    targetDir.mkdirs(); // this will also copy/move empty directories
    if (!targetDir.isDirectory())
        return false;

    if (createDir)
        targetDir = new File(targetDir, sourceDir.getName());
    if (move) {
        // in case of move just rename the directory to new location. The operation might fail
        // on a NFS or when copying accross different filesystems. In such cases, continue and copy
        // the files instead
        if (sourceDir.renameTo(targetDir))
            return true;
    } // else copy structure

    targetDir.mkdirs();
    boolean success = true;
    String[] fileList = sourceDir.list();
    if (fileList == null)
        return false; // I/O error or not a directory
    for (int i = 0; i < fileList.length; i++) {
        File f = new File(sourceDir, fileList[i]);
        if (f.isDirectory()) {
            success &= copyDirToDir(f, targetDir, move, filter, wt + File.separator + f.getName());
        } else {
            success &= copyFileToDir(f, targetDir, move, filter, wt + " file=" + f.getName());
        }
    }

    // in case of a move accross different filesystems, clean up now
    if (move) {
        sourceDir.delete();
    }
    return success;
}

From source file:org.ppojo.FolderTemplateFileQuery.java

@Override
public Set<String> getTemplateFiles() {
    CheckFolderExists();/*from  ww w .j  av  a2 s .c  om*/
    Set<String> result;
    FileFilter fileFilter = new WildcardFileFilter(_fileFilter);
    try {
        result = Files.walk(Paths.get(_path), _isRecursive ? Integer.MAX_VALUE : 1)
                .map(p -> new File(p.toUri())).filter(f -> fileFilter.accept(f)).map(f -> f.getAbsolutePath())
                .collect(Collectors.toSet());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:com.adaptris.core.fs.FsHelperTest.java

@Test
public void testCreateFilter() throws Exception {
    FileFilter filter = createFilter("", RegexFileFilter.class.getCanonicalName());
    // no op filter.
    assertTrue(filter.accept(new File("build.gradle")));
    assertNotEquals(RegexFileFilter.class, filter.getClass());
    filter = createFilter(".*", RegexFileFilter.class.getCanonicalName());
    assertEquals(RegexFileFilter.class, filter.getClass());
    assertTrue(filter.accept(new File("build.gradle")));

    // Just to fire the warning.
    assertEquals(AwkFilenameFilter.class,
            createFilter(".*", AwkFilenameFilter.class.getCanonicalName()).getClass());
}

From source file:org.pentaho.ctools.cpf.repository.utils.FileBasedResourceAccess.java

private List<IBasicFile> listFiles(List<IBasicFile> list, File root, FileFilter filter, boolean includeDirs,
        boolean showHiddenFilesAndFolders, int depth) {

    if (root.isDirectory()) {
        if (includeDirs && filter.accept(root)) {
            list.add(asBasicFile(root, relativizePath(root)));
        }//from  ww w. j a va2  s.c  o m
        if (depth != 0) {
            for (File file : root.listFiles()) {
                listFiles(list, file, filter, includeDirs, showHiddenFilesAndFolders, depth - 1);
            }
        }
    } else if (filter.accept(root)) {
        list.add(asBasicFile(root, relativizePath(root)));
    }
    return list;
}

From source file:se.jguru.nazgul.tools.codestyle.enforcer.rules.CorrectPackagingRule.java

/**
 * Adds all source file found by recursive search under sourceRoot to the
 * toPopulate List, using a width-first approach.
 *
 * @param fileOrDirectory      The file or directory to search for packages and [if a directory] recursively
 *                             search for further source files.
 * @param package2FileNamesMap A Map relating package names extracted by the PackageExtractors.
 *//*from   www .  j a  v a2 s  .c om*/
private void addPackages(final File fileOrDirectory,
        final SortedMap<String, SortedSet<String>> package2FileNamesMap) {

    for (PackageExtractor current : packageExtractors) {

        final FileFilter sourceFileDefinitionFilter = current.getSourceFileFilter();

        if (fileOrDirectory.isFile() && sourceFileDefinitionFilter.accept(fileOrDirectory)) {

            // Single source file to add.
            final String thePackage = current.getPackage(fileOrDirectory);

            SortedSet<String> sourceFileNames = package2FileNamesMap.get(thePackage);
            if (sourceFileNames == null) {
                sourceFileNames = new TreeSet<String>();
                package2FileNamesMap.put(thePackage, sourceFileNames);
            }

            // Done.
            sourceFileNames.add(fileOrDirectory.getName());

        } else if (fileOrDirectory.isDirectory()) {

            // Add the immediate source files
            for (File currentChild : fileOrDirectory.listFiles(sourceFileDefinitionFilter)) {
                addPackages(currentChild, package2FileNamesMap);
            }

            // Recurse into subdirectories
            for (File currentSubdirectory : fileOrDirectory.listFiles(DIRECTORY_FILTER)) {
                addPackages(currentSubdirectory, package2FileNamesMap);
            }
        }
    }
}

From source file:com.sap.prd.mobile.ios.mios.XCodeCopySourcesMojo.java

private void copy(final File source, final File targetDirectory, final FileFilter excludes) throws IOException {

    for (final File sourceFile : source.listFiles()) {
        final File destFile = new File(targetDirectory, sourceFile.getName());
        if (sourceFile.isDirectory()) {

            if (excludes.accept(sourceFile)) {
                copy(sourceFile, destFile, excludes);
            } else {
                getLog().info("File '" + sourceFile + "' ommited.");
            }//from  w  w w.j  a  va2  s . co m
        } else {
            FileUtils.copyFile(sourceFile, destFile);
            if (sourceFile.canExecute()) {
                destFile.setExecutable(true);
            }
            getLog().debug((destFile.canExecute() ? "Executable" : "File '") + sourceFile + "' copied to '"
                    + destFile + "'.");
        }
    }
}

From source file:org.talend.utils.io.FilesUtils.java

public static void copyFolder(File source, File target, boolean emptyTargetBeforeCopy,
        final FileFilter sourceFolderFilter, final FileFilter sourceFileFilter, boolean copyFolder)
        throws IOException {
    if (!target.exists()) {
        target.mkdirs();/*from w  w  w . j a v  a 2  s. co m*/
    }

    if (emptyTargetBeforeCopy) {
        emptyFolder(target);
    }

    FileFilter folderFilter = new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory()
                    && (sourceFolderFilter == null || sourceFolderFilter.accept(pathname));
        }

    };
    FileFilter fileFilter = new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            return !pathname.isDirectory() && (sourceFileFilter == null || sourceFileFilter.accept(pathname));
        }

    };
    File[] folders = source.listFiles(folderFilter);
    if (folders != null) {
        for (File current : folders) {
            if (copyFolder) {
                File newFolder = new File(target, current.getName());
                newFolder.mkdir();
                copyFolder(current, newFolder, emptyTargetBeforeCopy, sourceFolderFilter, sourceFileFilter,
                        copyFolder);
            } else {
                copyFolder(current, target, emptyTargetBeforeCopy, sourceFolderFilter, sourceFileFilter,
                        copyFolder);
            }
        }
    }

    File[] files = source.listFiles(fileFilter);
    if (files != null) {
        for (File current : files) {
            File out = new File(target, current.getName());
            copyFile(current, out);
        }
    }
}

From source file:Main.java

/**
 * Splits apart a OS separator delimited set of paths in a string into
 * multiple Strings. File component path strings are returned within a List
 * in the order they are found in the composite path string. Optionally, a
 * file filter can be used to filter out path strings to control the
 * components returned. If the filter is null all path components are
 * returned.//from w w  w .j  av  a2s.c  om
 * 
 * @param paths
 *            a set of paths delimited using the OS path separator
 * @param filter
 *            a FileFilter used to filter the return set
 * @return the filter accepted path component Strings in the order
 *         encountered
 */
public static final List getPaths(String paths, FileFilter filter) {
    int start = 0;
    int stop = -1;
    String path = null;
    ArrayList<String> list = new ArrayList<String>();

    // Abandon with no values if paths string is null
    if (paths == null || paths.trim().equals("")) {
        return list;
    }

    final int max = paths.length() - 1;

    // Loop spliting string using OS path separator: terminate
    // when the start index is at the end of the paths string.
    while (start < max) {
        stop = paths.indexOf(File.pathSeparatorChar, start);

        // The is no file sep between the start and the end of the string
        if (stop == -1) {
            // If we have a trailing path remaining without ending separator
            if (start < max) {
                // Last path is everything from start to the string's end
                path = paths.substring(start);

                // Protect against consecutive separators side by side
                if (!path.trim().equals("")) {
                    // If filter is null add path, if it is not null add the
                    // path only if the filter accepts the path component.
                    if (filter == null || filter.accept(new File(path))) {
                        list.add(path);
                    }
                }
            }

            break; // Exit loop no more path components left!
        }

        // There is a separator between start and the end if we got here!
        // start index is now at 0 or the index of last separator + 1
        // stop index is now at next separator in front of start index
        path = paths.substring(start, stop);

        // Protect against consecutive separators side by side
        if (!path.trim().equals("")) {
            // If filter is null add path, if it is not null add the path
            // only if the filter accepts the path component.
            if (filter == null || filter.accept(new File(path))) {
                list.add(path);
            }
        }

        // Advance start index past separator to start of next path comp
        start = stop + 1;
    }

    return list;
}