Example usage for java.nio.file Files walkFileTree

List of usage examples for java.nio.file Files walkFileTree

Introduction

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

Prototype

public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOException 

Source Link

Document

Walks a file tree.

Usage

From source file:org.jboss.as.test.integration.logging.handlers.SocketHandlerTestCase.java

@AfterClass
public static void tearDown() throws Exception {
    undeploy(DEPLOYMENT_NAME);/*  w w  w  .j ava  2 s.com*/
    // 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 {//from  w  w  w . ja  v  a 2  s  .c  o m
        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   ww w . j a  v a  2s. c o m*/
        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);
}

From source file:net.librec.data.convertor.appender.SocialDataAppender.java

/**
 * Read data from the data file. Note that we didn't take care of the
 * duplicated lines.// w  w  w  .ja  va 2s.  com
 *
 * @param inputDataPath
 *            the path of the data file
 * @throws IOException if I/O error occurs during reading
 */
private void readData(String inputDataPath) throws IOException {
    // Table {row-id, col-id, rate}
    Table<Integer, Integer, Double> dataTable = HashBasedTable.create();
    // Map {col-id, multiple row-id}: used to fast build a rating matrix
    Multimap<Integer, Integer> colMap = HashMultimap.create();
    // BiMap {raw id, inner id} userIds, itemIds
    final List<File> files = new ArrayList<File>();
    final ArrayList<Long> fileSizeList = new ArrayList<Long>();
    SimpleFileVisitor<Path> finder = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            fileSizeList.add(file.toFile().length());
            files.add(file.toFile());
            return super.visitFile(file, attrs);
        }
    };
    Files.walkFileTree(Paths.get(inputDataPath), finder);
    long allFileSize = 0;
    for (Long everyFileSize : fileSizeList) {
        allFileSize = allFileSize + everyFileSize.longValue();
    }
    // loop every dataFile collecting from walkFileTree
    for (File dataFile : files) {
        FileInputStream fis = new FileInputStream(dataFile);
        FileChannel fileRead = fis.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
        int len;
        String bufferLine = new String();
        byte[] bytes = new byte[BSIZE];
        while ((len = fileRead.read(buffer)) != -1) {
            buffer.flip();
            buffer.get(bytes, 0, len);
            bufferLine = bufferLine.concat(new String(bytes, 0, len)).replaceAll("\r", "\n");
            String[] bufferData = bufferLine.split("(\n)+");
            boolean isComplete = bufferLine.endsWith("\n");
            int loopLength = isComplete ? bufferData.length : bufferData.length - 1;
            for (int i = 0; i < loopLength; i++) {
                String line = new String(bufferData[i]);
                String[] data = line.trim().split("[ \t,]+");
                String userA = data[0];
                String userB = data[1];
                Double rate = (data.length >= 3) ? Double.valueOf(data[2]) : 1.0;
                if (userIds.containsKey(userA) && userIds.containsKey(userB)) {
                    int row = userIds.get(userA);
                    int col = userIds.get(userB);
                    dataTable.put(row, col, rate);
                    colMap.put(col, row);
                }
            }
            if (!isComplete) {
                bufferLine = bufferData[bufferData.length - 1];
            }
            buffer.clear();
        }
        fileRead.close();
        fis.close();
    }
    int numRows = userIds.size(), numCols = userIds.size();
    // build rating matrix
    userSocialMatrix = new SparseMatrix(numRows, numCols, dataTable, colMap);
    // release memory of data table
    dataTable = null;
}

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//from w w  w .j  ava2 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/*from   w w w . j  a  v  a  2  s. c  o 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/*from   ww  w  .  j av  a2 s. c  om*/
        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:edu.cornell.mannlib.vitro.webapp.freemarker.loader.FreemarkerTemplateLoader.java

private SortedSet<PathPieces> findAllMatches(PathPieces searchTerm) {
    PathPiecesFileVisitor visitor = new PathPiecesFileVisitor(searchTerm);
    try {//from  w  w w.j  a  v a2 s.com
        Files.walkFileTree(baseDir.toPath(), visitor);
    } catch (IOException e) {
        log.error(e);
    }
    return visitor.getMatches();
}

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 w  w  .  j  av  a 2 s . com*/

        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:com.netflix.genie.web.services.impl.DiskJobFileServiceImpl.java

/**
 * {@inheritDoc}//from w  w  w .ja  v  a 2  s  . c o  m
 */
@Override
public Set<JobFileState> getJobDirectoryFileState(final String jobId, final boolean calculateMd5)
        throws IOException {
    log.debug("Getting job directory state for job {} {} MD5", jobId, calculateMd5 ? "with" : "without");
    // TODO: It's possible the system should lock this directory while reading for consistent state?
    final Path jobDirectory = this.jobsDirRoot.resolve(jobId);
    this.createOrCheckDirectory(jobDirectory);

    final Set<JobFileState> jobDirectoryFiles = Sets.newHashSet();
    Files.walkFileTree(jobDirectory, new FileStateVisitor(jobDirectory, calculateMd5, jobDirectoryFiles));

    return jobDirectoryFiles;
}