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.apdplat.superword.tools.WordClassifierForWebster.java

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

                @Override//from  w ww. j av  a  2  s  . c o m
                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:org.phenotips.variantstore.input.exomiser6.tsv.Exomiser6TSVManager.java

@Override
public List<String> getAllIndividuals() {
    final List<String> list = new ArrayList<>();

    try {/*from  www. j a va 2  s  .com*/
        Files.walkFileTree(this.path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (attrs.isDirectory()) {
                    return FileVisitResult.CONTINUE;
                }
                String filename = file.getFileName().toString();
                String id = StringUtils.removeEnd(filename, suffix);
                list.add(id);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        logger.error("Error getting all individuals", e);
    }

    return list;
}

From source file:com.reactive.hzdfs.dll.JarModuleLoader.java

private Set<File> walkDirectory(Path directory) {
    final Set<File> walkedFiles = new LinkedHashSet<File>();
    try {/* w  w w.j  a  v a2s . c om*/
        registerWatch(directory);
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.preVisitDirectory(dir, attrs);
                registerWatch(dir);
                return fileVisitResult;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.visitFile(file, attrs);
                if (isJarFile(file.toFile()))
                    walkedFiles.add(file.toFile());

                return fileVisitResult;
            }

        });
    } catch (IOException e) {
        log.error("Failed to walk directory: " + directory.toString(), e);
    }
    return walkedFiles;
}

From source file:org.application.backupsync.PathName.java

public List<PathName> walk() throws IOException {
    final List<PathName> result;

    result = new ArrayList<>();

    if (Files.isReadable(this.path)) {
        Files.walkFileTree(this.path, new SimpleFileVisitor<Path>() {

            @Override//from   w  ww  . ja va2s  .c om
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                result.add(new PathName(file));
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException ex) {
                result.add(new PathName(dir));
                return FileVisitResult.CONTINUE;
            }
        });
    } else {
        throw new IllegalArgumentException("Directory cannot be read: " + this.path.toString());
    }
    return result;
}

From source file:com.yahoo.bard.webservice.util.Utils.java

/**
 * Delete files or directories in the specified path.
 *
 * @param path  The pathname/*from   www. ja  va2 s.c o  m*/
 */
public static void deleteFiles(String path) {
    Path directory = Paths.get(path);

    try {
        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 {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:lc.kra.servlet.FileManagerServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */// ww w .  j  av  a 2 s .co m
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Files files = null;
    File file = null, parent;
    String path = request.getParameter("path"), type = request.getContentType(),
            search = request.getParameter("search"), mode;

    if (path == null || !(file = new File(path)).exists())
        files = new Roots();
    else if (request.getParameter("zip") != null) {
        File zipFile = File.createTempFile(file.getName() + "-", ".zip");
        if (file.isFile())
            ZipUtil.addEntry(zipFile, file.getName(), file);
        else if (file.isDirectory())
            ZipUtil.pack(file, zipFile);
        downloadFile(response, zipFile, permamentName(zipFile.getName()), "application/zip");
    } else if (request.getParameter("delete") != null) {
        if (file.isFile())
            file.delete();
        else if (file.isDirectory()) {
            java.nio.file.Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    java.nio.file.Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    java.nio.file.Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } else if ((mode = request.getParameter("mode")) != null) {
        boolean add = mode.startsWith("+");
        if (mode.indexOf('r') > -1)
            file.setReadable(add);
        if (mode.indexOf('w') > -1)
            file.setWritable(add);
        if (mode.indexOf('x') > -1)
            file.setExecutable(add);
    } else if (file.isFile())
        downloadFile(response, file);
    else if (file.isDirectory()) {
        if (search != null && !search.isEmpty())
            files = new Search(file.toPath(), search);
        else if (type != null && type.startsWith("multipart/form-data")) {
            for (Part part : request.getParts()) {
                String name;
                if ((name = partFileName(part)) == null) //retrieves <input type="file" name="...">, no other (e.g. input) form fields
                    continue;
                if (request.getParameter("unzip") == null)
                    try (OutputStream output = new FileOutputStream(new File(file, name))) {
                        copyStream(part.getInputStream(), output);
                    }
                else
                    ZipUtil.unpack(part.getInputStream(), file);
            }
        } else
            files = new Directory(file);
    } else
        throw new ServletException("Unknown type of file or folder.");

    if (files != null) {
        final PrintWriter writer = response.getWriter();
        writer.println(
                "<!DOCTYPE html><html><head><style>*,input[type=\"file\"]::-webkit-file-upload-button{font-family:monospace}</style></head><body>");
        writer.println("<p>Current directory: " + files + "</p><pre>");
        if (!(files instanceof Roots)) {
            writer.print(
                    "<form method=\"post\"><label for=\"search\">Search Files:</label> <input type=\"text\" name=\"search\" id=\"search\" value=\""
                            + (search != null ? search : "")
                            + "\"> <button type=\"submit\">Search</button></form>");
            writer.print(
                    "<form method=\"post\" enctype=\"multipart/form-data\"><label for=\"upload\">Upload Files:</label> <button type=\"submit\">Upload</button> <button type=\"submit\" name=\"unzip\">Upload & Unzip</button> <input type=\"file\" name=\"upload[]\" id=\"upload\" multiple></form>");
            writer.println();
        }
        if (files instanceof Directory) {
            writer.println("+ <a href=\"?path=" + URLEncoder.encode(path, ENCODING) + "\">.</a>");
            if ((parent = file.getParentFile()) != null)
                writer.println("+ <a href=\"?path=" + URLEncoder.encode(parent.getAbsolutePath(), ENCODING)
                        + "\">..</a>");
            else
                writer.println("+ <a href=\"?path=\">..</a>");
        }

        for (File child : files.listFiles()) {
            writer.print(child.isDirectory() ? "+ " : "  ");
            writer.print("<a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING)
                    + "\" title=\"" + child.getAbsolutePath() + "\">" + child.getName() + "</a>");
            if (child.isDirectory())
                writer.print(" <a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING)
                        + "&zip\" title=\"download\">&#8681;</a>");
            if (search != null && !search.isEmpty())
                writer.print(" <a href=\"?path="
                        + URLEncoder.encode(child.getParentFile().getAbsolutePath(), ENCODING)
                        + "\" title=\"go to parent folder\">&#128449;</a>");
            writer.println();
        }
        writer.print("</pre></body></html>");
        writer.flush();
    }
}

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

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

                @Override/*  w  ww  . ja  va2s .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:org.jboss.as.test.integration.logging.handlers.SocketHandlerTestCase.java

@AfterClass
public static void tearDown() throws Exception {
    undeploy(DEPLOYMENT_NAME);/*from ww  w  . j  av a 2s. c o  m*/
    // Clear the temporary directory and delete it
    Files.walkFileTree(TEMP_DIR, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }
    });
    Files.deleteIfExists(TEMP_DIR);
}

From source file:org.talend.dataprep.dataset.store.content.file.LocalFileContentStore.java

@Override
public void clear() {
    try {/*w  w  w .  j  av  a2s  . com*/
        Path path = FileSystems.getDefault().getPath(storeLocation);
        if (!path.toFile().exists()) {
            return;
        }

        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                // .nfs files are handled by the OS and can be deleted after the visitor started.
                // Exceptions on such files can be safely ignored
                if (file.getFileName().toFile().getName().startsWith(".nfs")) { //$NON-NLS-1$
                    LOGGER.warn("unable to delete {}", file.getFileName(), exc);
                    return FileVisitResult.CONTINUE;
                }
                throw exc;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
                // Skip NFS file content
                if (!file.getFileName().toFile().getName().startsWith(".nfs")) { //$NON-NLS-1$
                    Files.delete(file);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
                if (e == null) {
                    return FileVisitResult.CONTINUE;
                } else {
                    // directory iteration failed
                    throw e;
                }
            }
        });
    } catch (IOException e) {
        LOGGER.error("Unable to clear local data set content.", e);
        throw new TDPException(DataSetErrorCodes.UNABLE_TO_CLEAR_DATASETS, e);
    }
}

From source file:org.zaproxy.admin.VerifyCoreZapVersionsEntries.java

private static void readZapVersionsFiles() throws Exception {
    Optional<String> path = Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator))
            .filter(e -> e.endsWith("/ZapVersionsTests")).findFirst();
    assertThat(path).as("The ZapVersionsTests directory was not found on the classpath.").isPresent();

    zapVersionsfiles = new ArrayList<>();
    Files.walkFileTree(Paths.get(path.get()), new SimpleFileVisitor<Path>() {

        @Override/*from  w ww  .j av a2 s  .  c om*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            String fileName = file.getFileName().toString();
            if (fileName.startsWith("ZapVersions") && fileName.endsWith(".xml")) {
                zapVersionsfiles.add(file);
            }
            return FileVisitResult.CONTINUE;
        }
    });

    Collections.sort(zapVersionsfiles);
}