Example usage for java.nio.file FileVisitOption FOLLOW_LINKS

List of usage examples for java.nio.file FileVisitOption FOLLOW_LINKS

Introduction

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

Prototype

FileVisitOption FOLLOW_LINKS

To view the source code for java.nio.file FileVisitOption FOLLOW_LINKS.

Click Source Link

Document

Follow symbolic links.

Usage

From source file:Test.java

public static void main(String[] args) {
    try {//  w  ww. j a  va 2 s .c om
        Path source = Paths.get("/home");
        Path target = Paths.get("/backup");
        Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new CopyDirectory(source, target));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:Search.java

public static void main(String[] args) throws IOException {

    Path searchFile = Paths.get("Demo.jpg");
    Search walk = new Search(searchFile);
    EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

    Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();
    for (Path root : dirs) {
        if (!walk.found) {
            Files.walkFileTree(root, opts, Integer.MAX_VALUE, walk);
        }//w ww. j av  a2  s . com
    }

    if (!walk.found) {
        System.out.println("The file " + searchFile + " was not found!");
    }
}

From source file:com.github.houbin217jz.thumbnail.Thumbnail.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("s", "src", true,
            "????????????");
    options.addOption("d", "dst", true, "");
    options.addOption("r", "ratio", true, "/??, 30%???0.3????????");
    options.addOption("w", "width", true, "(px)");
    options.addOption("h", "height", true, "?(px)");
    options.addOption("R", "recursive", false, "???????");

    HelpFormatter formatter = new HelpFormatter();
    String formatstr = "java -jar thumbnail.jar " + "[-s/--src <path>] " + "[-d/--dst <path>] "
            + "[-r/--ratio double] " + "[-w/--width integer] " + "[-h/--height integer] " + "[-R/--recursive] ";

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//from  w ww .  java 2  s .  co m
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        formatter.printHelp(formatstr, options);
        return;
    }

    final Path srcDir, dstDir;
    final Integer width, height;
    final Double ratio;

    //
    if (cmd.hasOption("s")) {
        srcDir = Paths.get(cmd.getOptionValue("s")).toAbsolutePath();
    } else {
        srcDir = Paths.get("").toAbsolutePath(); //??
    }

    //
    if (cmd.hasOption("d")) {
        dstDir = Paths.get(cmd.getOptionValue("d")).toAbsolutePath();
    } else {
        formatter.printHelp(formatstr, options);
        return;
    }

    if (!Files.exists(srcDir, LinkOption.NOFOLLOW_LINKS)
            || !Files.isDirectory(srcDir, LinkOption.NOFOLLOW_LINKS)) {
        System.out.println("[" + srcDir.toAbsolutePath() + "]??????");
        return;
    }

    if (Files.exists(dstDir, LinkOption.NOFOLLOW_LINKS)) {
        if (!Files.isDirectory(dstDir, LinkOption.NOFOLLOW_LINKS)) {
            //????????
            System.out.println("????????");
            return;
        }
    } else {
        //????????
        try {
            Files.createDirectories(dstDir);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

    //??
    if (cmd.hasOption("w") && cmd.hasOption("h")) {
        try {
            width = Integer.valueOf(cmd.getOptionValue("width"));
            height = Integer.valueOf(cmd.getOptionValue("height"));
        } catch (NumberFormatException e) {
            System.out.println("??????");
            return;
        }
    } else {
        width = null;
        height = null;
    }

    //?
    if (cmd.hasOption("r")) {
        try {
            ratio = Double.valueOf(cmd.getOptionValue("r"));
        } catch (NumberFormatException e) {
            System.out.println("?????");
            return;
        }
    } else {
        ratio = null;
    }

    if (width != null && ratio != null) {
        System.out.println("??????????????");
        return;
    }

    if (width == null && ratio == null) {
        System.out.println("????????????");
        return;
    }

    //
    int maxDepth = 1;
    if (cmd.hasOption("R")) {
        maxDepth = Integer.MAX_VALUE;
    }

    try {
        //Java 7 ??@see http://docs.oracle.com/javase/jp/7/api/java/nio/file/Files.html
        Files.walkFileTree(srcDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), maxDepth,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                            throws IOException {

                        //???&???
                        String filename = path.getFileName().toString().toLowerCase();

                        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
                            //Jpeg??

                            /*
                             * relative??:
                             * rootPath: /a/b/c/d
                             * filePath: /a/b/c/d/e/f.jpg
                             * rootPath.relativize(filePath) = e/f.jpg
                             */

                            /*
                             * resolve??
                             * rootPath: /a/b/c/output
                             * relativePath: e/f.jpg
                             * rootPath.resolve(relativePath) = /a/b/c/output/e/f.jpg
                             */

                            Path dst = dstDir.resolve(srcDir.relativize(path));

                            if (!Files.exists(dst.getParent(), LinkOption.NOFOLLOW_LINKS)) {
                                Files.createDirectories(dst.getParent());
                            }
                            doResize(path.toFile(), dst.toFile(), width, height, ratio);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:file.FileOperatorTest.java

/**
 *http://stackoverflow.com/questions/16524065/is-filevisitoption-follow-links-the-only-filevisitoption-available
 *//*from w  w  w. ja v  a  2  s. c om*/
public static List<Path> testWalkFileWithStream() {
    try {
        System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20");
        long a = System.currentTimeMillis();
        Files.walk(Paths.get(ROOT_DIR), FileVisitOption.FOLLOW_LINKS).parallel().filter(x -> {
            return x.toFile().isFile();
        }).forEach(x -> {
            // Files.copy(x, Paths.get(""), CopyOption )
        });
        long b = System.currentTimeMillis();
        System.out.println(":" + (b - a));
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.kappaware.logtrawler.DirWatcher.java

/**
 * //from  www.ja va  2  s.  co m
 * @param path      The path to monitor
 * @param queue      Where to store events
 * @throws IOException 
 */
DirWatcher(Config.Agent.Folder dir, BlockingSetQueue<FileEvent> queue) throws IOException {
    Path path = Paths.get(dir.getPath());
    this.followLink = dir.getFollowLink();
    this.queue = queue;
    this.watcher = FileSystems.getDefault().newWatchService();
    this.pathByKey = new HashMap<WatchKey, Path>();
    this.fileVisitOptions = new HashSet<FileVisitOption>();
    if (this.followLink) {
        this.fileVisitOptions.add(FileVisitOption.FOLLOW_LINKS);
    }
    if (dir.getExcludedPaths() != null && dir.getExcludedPaths().size() > 0) {
        exclusions = new Vector<Exclusion>(dir.getExcludedPaths().size());
        for (String excludedPath : dir.getExcludedPaths()) {
            exclusions.add(new Exclusion(dir.getPath(), excludedPath));
        }
    }
    log.info(String.format("Scanning %s ...", path));
    this.registerWithSub(path, FileEvent.Type.FILE_INIT);
    this.watcherThread = new WatcherThread();
    this.watcherThread.setDaemon(true);
    this.watcherThread.start();
}

From source file:de.thomasbolz.renamer.Renamer.java

/**
 * Step 1 of the renaming process:/*from  w w w  . j ava  2  s.  com*/
 * Analysis steps in the renaming process. Walks the whole file tree of the source directory and creates a CopyTask
 * for each file or directory that is found and does not match the exclusion list.
 * @return a list of all CopyTasks
 */
public Map<Path, List<CopyTask>> prepareCopyTasks() {

    try {
        Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {

                    /**
                     * If we find a directory create/copy it and add a counter
                     *
                     * @param dir
                     * @param attrs
                     * @return
                     * @throws java.io.IOException
                     */
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        Path targetdir = target.resolve(source.relativize(dir));
                        copyTasks.put(dir, new ArrayList<CopyTask>());
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        if (!file.getFileName().toString().toLowerCase().matches(EXLUSION_REGEX)) {
                            copyTasks.get(file.getParent()).add(new CopyTask(file, null));
                        } else {
                            excludedFiles.add(file);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
    } catch (IOException e) {
        e.printStackTrace();
    }
    sortCopyTasks();
    //        generateTargetFilenames();
    return copyTasks;
}

From source file:com.netflix.spinnaker.halyard.core.registry.v1.GitProfileReader.java

@Override
public InputStream readArchiveProfile(String artifactName, String version, String profileName)
        throws IOException {
    Path profilePath = Paths.get(profilePath(artifactName, version, profileName));

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(os);

    ArrayList<Path> filePathsToAdd = java.nio.file.Files
            .walk(profilePath, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)
            .filter(path -> path.toFile().isFile()).collect(Collectors.toCollection(ArrayList::new));

    for (Path path : filePathsToAdd) {
        TarArchiveEntry tarEntry = new TarArchiveEntry(path.toFile(), profilePath.relativize(path).toString());
        int permissions = FileModeUtils.getFileMode(Files.getPosixFilePermissions(path));
        permissions = FileModeUtils.setFileBit(permissions);
        tarEntry.setMode(permissions);//from  ww w  .j a v  a2s .co m
        tarArchive.putArchiveEntry(tarEntry);
        IOUtils.copy(Files.newInputStream(path), tarArchive);
        tarArchive.closeArchiveEntry();
    }

    tarArchive.finish();
    tarArchive.close();

    return new ByteArrayInputStream(os.toByteArray());
}

From source file:com.spotify.docker.client.CompressedDirectory.java

/**
 * This method creates a gzip tarball of the specified directory. File permissions will be
 * retained. The file will be created in a temporary directory using the {@link
 * Files#createTempFile(String, String, FileAttribute[])} method. The returned object is
 * auto-closeable, and upon closing it, the archive file will be deleted.
 *
 * @param directory the directory to compress
 * @return a Path object representing the compressed directory
 * @throws IOException if the compressed directory could not be created.
 *///  w w w  . j a  va2 s.  c om
public static CompressedDirectory create(final Path directory) throws IOException {
    final Path file = Files.createTempFile("docker-client-", ".tar.gz");

    final Path dockerIgnorePath = directory.resolve(".dockerignore");
    final ImmutableSet<PathMatcher> ignoreMatchers = parseDockerIgnore(dockerIgnorePath);

    try (final OutputStream fileOut = Files.newOutputStream(file);
            final GzipCompressorOutputStream gzipOut = new GzipCompressorOutputStream(fileOut);
            final TarArchiveOutputStream tarOut = new TarArchiveOutputStream(gzipOut)) {
        tarOut.setLongFileMode(LONGFILE_POSIX);
        tarOut.setBigNumberMode(BIGNUMBER_POSIX);
        Files.walkFileTree(directory, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new Visitor(directory, ignoreMatchers, tarOut));

    } catch (Throwable t) {
        // If an error occurs, delete temporary file before rethrowing exception.
        try {
            Files.delete(file);
        } catch (IOException e) {
            // So we don't lose track of the reason the file was deleted... might be important
            t.addSuppressed(e);
        }

        throw t;
    }

    return new CompressedDirectory(file);
}

From source file:com.netflix.spinnaker.halyard.core.registry.v1.LocalDiskProfileReader.java

public InputStream readArchiveProfileFrom(Path profilePath) throws IOException {

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(os);

    ArrayList<Path> filePathsToAdd = java.nio.file.Files
            .walk(profilePath, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)
            .filter(path -> path.toFile().isFile()).collect(Collectors.toCollection(ArrayList::new));

    for (Path path : filePathsToAdd) {
        TarArchiveEntry tarEntry = new TarArchiveEntry(path.toFile(), profilePath.relativize(path).toString());
        tarArchive.putArchiveEntry(tarEntry);
        IOUtils.copy(Files.newInputStream(path), tarArchive);
        tarArchive.closeArchiveEntry();//from  ww w  .  ja v  a 2  s.c om
    }

    tarArchive.finish();
    tarArchive.close();

    return new ByteArrayInputStream(os.toByteArray());
}

From source file:com.netflix.genie.common.internal.dto.JobDirectoryManifest.java

/**
 * Create a manifest from the given job directory.
 *
 * @param directory              The job directory to create a manifest from
 * @param calculateFileChecksums Whether or not to calculate checksums for each file added to the manifest
 * @throws IOException If there is an error reading the directory
 *///from   w w w .  j a  v  a  2  s .c  o  m
public JobDirectoryManifest(final Path directory, final boolean calculateFileChecksums) throws IOException {
    // Walk the directory
    final ImmutableMap.Builder<String, ManifestEntry> builder = ImmutableMap.builder();
    final ManifestVisitor manifestVisitor = new ManifestVisitor(directory, builder, calculateFileChecksums);
    final EnumSet<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    Files.walkFileTree(directory, options, Integer.MAX_VALUE, manifestVisitor);
    this.entries = builder.build();

    final ImmutableSet.Builder<ManifestEntry> filesBuilder = ImmutableSet.builder();
    final ImmutableSet.Builder<ManifestEntry> directoriesBuilder = ImmutableSet.builder();

    long sizeOfFiles = 0L;
    for (final ManifestEntry entry : this.entries.values()) {
        if (entry.isDirectory()) {
            directoriesBuilder.add(entry);
        } else {
            filesBuilder.add(entry);
            sizeOfFiles += entry.getSize();
        }
    }

    this.totalSizeOfFiles = sizeOfFiles;
    this.directories = directoriesBuilder.build();
    this.files = filesBuilder.build();
    this.numDirectories = this.directories.size();
    this.numFiles = this.files.size();
}