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:ufo.test.spark.service.WordCountServiceTest.java

private void deleteRecursively(Path path) throws IOException {
    if (Files.exists(path)) {
        //delete recursively
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override/* w  w w  .  ja va 2s.c  om*/
            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;
            }
        });
    }
    assertFalse(Files.exists(path));
}

From source file:org.phenotips.variantstore.input.vcf.VCFManager.java

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

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

    return list;
}

From source file:org.zanata.sync.jobs.cache.RepoCacheImpl.java

private long copyDir(Path source, Path target) throws IOException {
    Files.createDirectories(target);
    AtomicLong totalSize = new AtomicLong(0);
    Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
            new SimpleFileVisitor<Path>() {
                @Override//  www .  j  a v  a2 s.c  o  m
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    Path targetdir = target.resolve(source.relativize(dir));
                    try {
                        if (Files.isDirectory(targetdir) && Files.exists(targetdir)) {
                            return CONTINUE;
                        }
                        Files.copy(dir, targetdir, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    } catch (FileAlreadyExistsException e) {
                        if (!Files.isDirectory(targetdir)) {
                            throw e;
                        }
                    }
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (Files.isRegularFile(file)) {
                        totalSize.accumulateAndGet(Files.size(file), (l, r) -> l + r);
                    }
                    Path targetFile = target.resolve(source.relativize(file));

                    // only copy to target if it doesn't exist or it exist but the content is different
                    if (!Files.exists(targetFile)
                            || !com.google.common.io.Files.equal(file.toFile(), targetFile.toFile())) {
                        Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    }
                    return CONTINUE;
                }
            });
    return totalSize.get();
}

From source file:de.hybris.platform.media.storage.impl.MediaCacheRecreatorTest.java

private void cleanCacheFolder(final String folderName) throws IOException {
    Files.walkFileTree(Paths.get(System.getProperty("java.io.tmpdir"), folderName),
            new SimpleFileVisitor<Path>() {
                @Override//from w  ww  .ja v a 2  s  .  c  om
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(final Path file, final IOException exc)
                        throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }
            });
}

From source file:org.esa.nest.util.FileIOUtils.java

public static void deleteFolder(final Path source) throws IOException {
    Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
        @Override/*from ww  w . j a v  a 2  s . c o m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            if (exc == null) {
                Files.delete(dir);
                return CONTINUE;
            } else {
                throw exc;
            }
        }
    });
}

From source file:ch.bender.evacuate.Runner.java

/**
 * run//from www  .  jav a  2  s.c  o m
 * <p>
 * @throws Exception 
 */
public void run() throws Exception {
    checkDirectories();
    initExcludeMatchers();

    myEvacuateCandidates = new TreeMap<>();
    myFailedChainPreparations = Collections.synchronizedMap(new HashMap<>());
    myFutures = new HashSet<>();
    myExclusionDirCount = 0;
    myEvacuationDirCount = 0;
    myExclusionFileCount = 0;
    myEvacuationFileCount = 0;

    Files.walkFileTree(myBackupDir, new SimpleFileVisitor<Path>() {
        /**
         * @see java.nio.file.SimpleFileVisitor#visitFileFailed(java.lang.Object, java.io.IOException)
         */
        @Override
        public FileVisitResult visitFileFailed(Path aFile, IOException aExc) throws IOException {
            if ("System Volume Information".equals((aFile.getFileName().toString()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            throw aExc;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            return Runner.this.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if ("System Volume Information".equals((dir.getFileName()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            return Runner.this.preVisitDirectory(dir, attrs);
        }

    });

    if (myEvacuateCandidates.size() == 0) {
        myLog.info("No candidates for evacuation found");
    } else {
        StringBuilder sb = new StringBuilder("\nFound candidates for evacuation:");
        myEvacuateCandidates.keySet().forEach(p -> sb.append("\n    " + p.toString()));
        myLog.info(sb.toString());
    }

    if (myDryRun) {
        myLog.debug("DryRun flag is set. Doing nothing");
        return;
    }

    if (myFutures.size() > 0) {
        myLog.debug("Waiting for all async tasks to complete");
        CompletableFuture.allOf(myFutures.toArray(new CompletableFuture[myFutures.size()])).get();
    }

    if (myFailedChainPreparations.size() > 0) {
        for (Path path : myFailedChainPreparations.keySet()) {
            myLog.error("exception occured", myFailedChainPreparations.get(path));
        }

        throw new Exception("chain preparation failed. See above error messages");
    }

    for (Path src : myEvacuateCandidates.keySet()) {
        Path dst = myEvacuateCandidates.get(src);
        Path dstParent = dst.getParent();

        if (Files.notExists(dstParent)) {
            Files.createDirectories(dstParent); // FUTURE: overtake file attributes from src
        }

        if (myMove) {
            try {
                myLog.debug(
                        "Moving file system object \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
            } catch (AtomicMoveNotSupportedException e) {
                myLog.warn("Atomic move not supported. Try copy and then delete");

                if (Files.isDirectory(src)) {
                    myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                    FileUtils.copyDirectory(src.toFile(), dst.toFile());
                    myLog.debug("Delete folder \"" + src.toString() + "\"");
                    FileUtils.deleteDirectory(src.toFile());
                } else {
                    myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                    FileUtils.copyFile(src.toFile(), dst.toFile());
                    myLog.debug("Delete file \"" + src.toString() + "\"");
                    Files.delete(src);
                }
            }

        } else {
            if (Files.isDirectory(src)) {
                myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                FileUtils.copyDirectory(src.toFile(), dst.toFile());
            } else {
                myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                FileUtils.copyFile(src.toFile(), dst.toFile());
            }
        }
    }

    myLog.info("\nSuccessfully terminated." + "\n             Evacuated  Skipped" + "\n    Files  : "
            + StringUtils.leftPad("" + myEvacuationDirCount, 9)
            + StringUtils.leftPad("" + myExclusionDirCount, 9) + "\n    Folders: "
            + StringUtils.leftPad("" + myEvacuationFileCount, 9)
            + StringUtils.leftPad("" + myExclusionFileCount, 9));
}

From source file:org.nuxeo.connect.update.standalone.PackageTestCase.java

/** Zips a directory into the given ZIP file. */
protected void createZip(File zip, Path basePath) throws IOException {
    try (ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip)))) {
        Files.walkFileTree(basePath, new SimpleFileVisitor<Path>() {
            @Override//from ww w. j a v  a2  s  . c  o  m
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                if (attrs.isDirectory()) {
                    return FileVisitResult.CONTINUE;
                }
                String rel = basePath.relativize(path).toString();
                if (rel.startsWith(".")) {
                    return FileVisitResult.CONTINUE;
                }
                zout.putNextEntry(new ZipEntry(rel));
                try (InputStream in = Files.newInputStream(path)) {
                    org.apache.commons.io.IOUtils.copy(in, zout);
                }
                zout.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
        zout.flush();
    }
}

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.//from w  w  w .j av  a  2 s  .  co  m
 *
 * @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.neo4j.graphdb.LuceneLabelScanStoreIT.java

private void corruptIndex(NeoStoreDataSource dataSource) throws IOException {
    File labelScanStoreDirectory = getLabelScanStoreDirectory(dataSource);
    Files.walkFileTree(labelScanStoreDirectory.toPath(), new SimpleFileVisitor<Path>() {
        @Override/*from   w w w.j  a va 2  s.c om*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.write(file, ArrayUtils.add(Files.readAllBytes(file), (byte) 7));
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:com.cloudbees.clickstack.util.Files2.java

public static void chmodReadOnly(@Nonnull Path path) throws RuntimeIOException {

    SimpleFileVisitor<Path> setReadOnlyFileVisitor = new SimpleFileVisitor<Path>() {
        @Override//from w w  w  . j  a v  a  2  s. c o  m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (Files.isDirectory(file)) {
                throw new IllegalStateException("no dir expected here");
            } else {
                Files.setPosixFilePermissions(file, PERMISSION_R);
            }
            return super.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            Files.setPosixFilePermissions(dir, PERMISSION_RX);
            return super.preVisitDirectory(dir, attrs);
        }
    };
    try {
        Files.walkFileTree(path, setReadOnlyFileVisitor);
    } catch (IOException e) {
        throw new RuntimeIOException("Exception changing permissions to readonly for " + path, e);
    }
}