Example usage for java.nio.file SimpleFileVisitor SimpleFileVisitor

List of usage examples for java.nio.file SimpleFileVisitor SimpleFileVisitor

Introduction

In this page you can find the example usage for java.nio.file SimpleFileVisitor SimpleFileVisitor.

Prototype

protected SimpleFileVisitor() 

Source Link

Document

Initializes a new instance of this class.

Usage

From source file:org.sonarsource.commandlinezip.ZipUtils7.java

public static void fastZip(final Path srcDir, Path zip) throws IOException {
    try (final OutputStream out = FileUtils.openOutputStream(zip.toFile());
            final ZipOutputStream zout = new ZipOutputStream(out)) {
        zout.setMethod(ZipOutputStream.STORED);
        Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
            @Override//w  ww  . j a va 2 s.  c om
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                try (InputStream in = new BufferedInputStream(new FileInputStream(file.toFile()))) {
                    String entryName = srcDir.relativize(file).toString();
                    ZipEntry entry = new ZipEntry(entryName);
                    zout.putNextEntry(entry);
                    IOUtils.copy(in, zout);
                    zout.closeEntry();
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (dir.equals(srcDir)) {
                    return FileVisitResult.CONTINUE;
                }

                String entryName = srcDir.relativize(dir).toString();
                ZipEntry entry = new ZipEntry(entryName);
                zout.putNextEntry(entry);
                zout.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

From source file:org.phenotips.variantstore.shared.ResourceManager.java

/**
 * Copy resources recursively from a path on the filesystem to the destination folder.
 *
 * @param source/*  ww  w  . j  ava2  s . co  m*/
 * @param dest
 * @throws IOException
 */
private static void copyResourcesFromFilesystem(final Path source, final Path dest) throws IOException {
    Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Path relative = source.relativize(file);
            Files.copy(file, dest.resolve(relative));
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            Path relative = source.relativize(dir);
            Files.createDirectory(dest.resolve(relative));
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:services.ImportExportService.java

public static void importDirectoryRecursive(final Project project, Path root) throws IOException {
    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
        @Override// www  . j a  va  2s  .c  o  m
        public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
            if (PathService.isImage(path)) {
                DatabaseImage image = DatabaseImage.forPath(path);
                if (!image.imported && hasFileToImport(image))
                    importData(project, image);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:com.liferay.sync.engine.SyncSystemTest.java

protected static void cleanUp(long delay) throws Exception {
    for (long syncAccountId : _syncAccountIds.values()) {
        SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(syncAccountId);

        if (syncAccount == null) {
            return;
        }/*from  w  ww . j a  va 2 s .  c o  m*/

        Files.walkFileTree(Paths.get(syncAccount.getFilePathName()), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult postVisitDirectory(Path filePath, IOException ioe) throws IOException {

                Files.deleteIfExists(filePath);

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path filePath, BasicFileAttributes basicFileAttributes)
                    throws IOException {

                Files.deleteIfExists(filePath);

                return FileVisitResult.CONTINUE;
            }

        });
    }

    pause(delay);

    SyncEngine.stop();

    Files.walkFileTree(Paths.get(_rootFilePathName), new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult postVisitDirectory(Path filePath, IOException ioe) throws IOException {

            Files.delete(filePath);

            return FileVisitResult.CONTINUE;
        }

    });

    for (long syncAccountId : _syncAccountIds.values()) {
        SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(syncAccountId);

        SyncSystemTestUtil.deleteUser(syncAccount.getUserId(), _syncAccount.getSyncAccountId());

        SyncAccountService.deleteSyncAccount(syncAccountId);
    }

    SyncAccountService.deleteSyncAccount(_syncAccount.getSyncAccountId());
}

From source file:org.apdplat.superword.tools.WordClassifier.java

public static void parseZip(String zipFile) {
    LOGGER.info("?ZIP" + zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) {
        for (Path path : fs.getRootDirectories()) {
            LOGGER.info("?" + path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override//from  ww w.j  a v  a2  s .c  om
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/origin-html-temp.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    parseFile(temp.toFile().getAbsolutePath());
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    } catch (Exception e) {
        LOGGER.error("?", e);
    }
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceCopyWebdavDirectoryTestExecutionListener.java

private void cleanDirectory(Path directory) {
    if (!Files.isDirectory(directory)) {
        return;//w w w  .  j av  a2s  .  com
    }

    try {
        log.debug("Remove all Contents of Directory {}", directory.toAbsolutePath().toString());
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (!Files.isSameFile(dir, directory)) {
                    Files.delete(dir);
                }
                return FileVisitResult.CONTINUE;
            }
        });
        Files.delete(directory);
    } catch (IOException e) {
        throw new RuntimeException(
                String.format("IOException while cleaning Directory %s", directory.toAbsolutePath().toString()),
                e);
    }
}

From source file:com.garyclayburg.filesystem.WatchDir.java

/**
 * Register the given directory, and all its sub-directories, with the
 * WatchService./* ww  w  . j a  v  a2 s  . c o  m*/
 */
private void registerAll(final Path start) throws IOException {
    // register directory and sub-directories
    Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            register(dir);
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:org.openhab.tools.analysis.checkstyle.PackageExportsNameCheck.java

/**
 * Filter and return the packages from the source directory. Only not excluded packages will be returned.
 *
 * @param sourcePath - The full path of the source directory
 * @return {@link Set } of {@link String }s with the package names.
 * @throws IOException if an I/O error is thrown while visiting files
 *///  w ww.j av a2s  .co m
private Set<String> getFilteredPackagesFromSourceDirectory(Path sourcePath) throws IOException {
    Set<String> packages = new HashSet<>();
    // No symbolic links are expected in the source directory
    if (Files.exists(sourcePath, LinkOption.NOFOLLOW_LINKS)) {
        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
                Path packageRelativePath = sourcePath.relativize(path.getParent());
                String packageName = packageRelativePath.toString()
                        .replaceAll(Matcher.quoteReplacement(File.separator), ".");

                if (!isExcluded(packageName)) {
                    packages.add(packageName);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }

    return packages;
}

From source file:org.wte4j.examples.showcase.server.hsql.ShowCaseDbInitializerTest.java

private void deleteDirectory(Path path) throws IOException {

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override/* ww w  .jav a2s  .c  om*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.deleteIfExists(file);
            return super.visitFile(file, attrs);
        }
    });
    Files.deleteIfExists(path);

}

From source file:net.mozq.picto.core.ProcessCore.java

public static void findFiles(ProcessCondition processCondition, Consumer<ProcessData> processDataSetter,
        BooleanSupplier processStopper) throws IOException {

    Set<FileVisitOption> fileVisitOptionSet;
    if (processCondition.isFollowLinks()) {
        fileVisitOptionSet = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    } else {//  ww  w.  j a  va2 s.c  o  m
        fileVisitOptionSet = Collections.emptySet();
    }

    Files.walkFileTree(processCondition.getSrcRootPath(), fileVisitOptionSet, processCondition.getDept(),
            new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (processStopper.getAsBoolean()) {
                        return FileVisitResult.TERMINATE;
                    }

                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                    if (attrs.isDirectory()) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    if (processStopper.getAsBoolean()) {
                        return FileVisitResult.TERMINATE;
                    }

                    if (!processCondition.getPathFilter().accept(file, attrs)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    Path rootRelativeSubPath = processCondition.getSrcRootPath().relativize(file.getParent());

                    ImageMetadata imageMetadata = getImageMetadata(file);

                    Date baseDate;
                    if (processCondition.isChangeFileCreationDate()
                            || processCondition.isChangeFileModifiedDate()
                            || processCondition.isChangeFileAccessDate()
                            || processCondition.isChangeExifDate()) {
                        baseDate = getBaseDate(processCondition, file, attrs, imageMetadata);
                    } else {
                        baseDate = null;
                    }

                    String destSubPathname = processCondition.getDestSubPathFormat().format(varName -> {
                        try {
                            switch (varName) {
                            case "Now":
                                return new Date();
                            case "ParentSubPath":
                                return rootRelativeSubPath.toString();
                            case "FileName":
                                return file.getFileName().toString();
                            case "BaseName":
                                return FileUtilz.getBaseName(file.getFileName().toString());
                            case "Extension":
                                return FileUtilz.getExt(file.getFileName().toString());
                            case "Size":
                                return Long.valueOf(Files.size(file));
                            case "CreationDate":
                                return (processCondition.isChangeFileCreationDate()) ? baseDate
                                        : new Date(attrs.creationTime().toMillis());
                            case "ModifiedDate":
                                return (processCondition.isChangeFileModifiedDate()) ? baseDate
                                        : new Date(attrs.lastModifiedTime().toMillis());
                            case "AccessDate":
                                return (processCondition.isChangeFileAccessDate()) ? baseDate
                                        : new Date(attrs.lastAccessTime().toMillis());
                            case "PhotoTakenDate":
                                return (processCondition.isChangeExifDate()) ? baseDate
                                        : getPhotoTakenDate(file, imageMetadata);
                            case "Width":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXIF_IMAGE_WIDTH);
                            case "Height":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXIF_IMAGE_LENGTH);
                            case "FNumber":
                                return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FNUMBER);
                            case "Aperture":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
                            case "MaxAperture":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_MAX_APERTURE_VALUE);
                            case "ISO":
                                return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_ISO);
                            case "FocalLength":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_FOCAL_LENGTH); // ?
                            case "FocalLength35mm":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_FOCAL_LENGTH_IN_35MM_FORMAT);
                            case "ShutterSpeed":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_SHUTTER_SPEED_VALUE);
                            case "Exposure":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE); // 
                            case "ExposureTime":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXPOSURE_TIME); // 
                            case "ExposureMode":
                                return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_MODE);
                            case "ExposureProgram":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXPOSURE_PROGRAM);
                            case "Brightness":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_BRIGHTNESS_VALUE);
                            case "WhiteBalance":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_WHITE_BALANCE_1);
                            case "LightSource":
                                return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_LIGHT_SOURCE);
                            case "Lens":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS);
                            case "LensMake":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MAKE);
                            case "LensModel":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MODEL);
                            case "LensSerialNumber":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_LENS_SERIAL_NUMBER);
                            case "Make":
                                return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MAKE);
                            case "Model":
                                return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MODEL);
                            case "SerialNumber":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_SERIAL_NUMBER);
                            case "Software":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_SOFTWARE);
                            case "ProcessingSoftware":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_PROCESSING_SOFTWARE);
                            case "OwnerName":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_OWNER_NAME);
                            case "CameraOwnerName":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_CAMERA_OWNER_NAME);
                            case "GPSLat":
                                return getEXIFGpsLat(imageMetadata);
                            case "GPSLatDeg":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE,
                                        0);
                            case "GPSLatMin":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE,
                                        1);
                            case "GPSLatSec":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE,
                                        2);
                            case "GPSLatRef":
                                return getEXIFStringValue(imageMetadata,
                                        GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF);
                            case "GPSLon":
                                return getEXIFGpsLon(imageMetadata);
                            case "GPSLonDeg":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE,
                                        0);
                            case "GPSLonMin":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE,
                                        1);
                            case "GPSLonSec":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE,
                                        2);
                            case "GPSLonRef":
                                return getEXIFStringValue(imageMetadata,
                                        GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF);
                            case "GPSAlt":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE);
                            case "GPSAltRef":
                                return getEXIFIntValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE_REF);
                            default:
                                throw new PictoInvalidDestinationPathException(Messages
                                        .getString("message.warn.invalid.destSubPath.varName", varName));
                            }
                        } catch (PictoException e) {
                            throw e;
                        } catch (Exception e) {
                            throw new PictoInvalidDestinationPathException(
                                    Messages.getString("message.warn.invalid.destSubPath.pattern"), e);
                        }
                    });

                    Path destSubPath = processCondition.getDestRootPath().resolve(destSubPathname).normalize();

                    if (!destSubPath.startsWith(processCondition.getDestRootPath())) {
                        throw new PictoInvalidDestinationPathException(
                                Messages.getString("message.warn.invalid.destination.path", destSubPath));
                    }

                    ProcessData processData = new ProcessData();
                    processData.setSrcPath(file);
                    processData.setSrcFileAttributes(attrs);
                    processData.setDestPath(destSubPath);
                    processData.setBaseDate(baseDate);

                    processDataSetter.accept(processData);

                    return FileVisitResult.CONTINUE;
                }
            });
}