Java Code Examples for java.nio.file.attribute.BasicFileAttributes

The following are top voted examples for showing how to use java.nio.file.attribute.BasicFileAttributes. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: JavacFileManager.java   View source code 7 votes vote down vote up
public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException, SecurityException {
    this.archivePath = archivePath;
    if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) {
        Map<String,String> env = Collections.singletonMap("multi-release", multiReleaseValue);
        FileSystemProvider jarFSProvider = fsInfo.getJarFSProvider();
        Assert.checkNonNull(jarFSProvider, "should have been caught before!");
        this.fileSystem = jarFSProvider.newFileSystem(archivePath, env);
    } else {
        this.fileSystem = FileSystems.newFileSystem(archivePath, null);
    }
    packages = new HashMap<>();
    for (Path root : fileSystem.getRootDirectories()) {
        Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                        if (isValid(dir.getFileName())) {
                            packages.put(new RelativeDirectory(root.relativize(dir).toString()), dir);
                            return FileVisitResult.CONTINUE;
                        } else {
                            return FileVisitResult.SKIP_SUBTREE;
                        }
                    }
                });
    }
}
 
Example 2
Project: MFM   File: FileUtils.java   View source code 7 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
    // NOTE if we are searching for Directories also file may be NULL ??
    if (file == null) {
        System.out.println("visitFile File: is NULL");
        return CONTINUE;
    }
    if (file.getFileName().equals(fileName)) {
        System.out.println("Located file: " + file);
        if (!matchWithoutSuffix) {
            MFM_FindFile.file = file;
            exists = true;
            return TERMINATE;
        }
    }  // Do we have a base file name, extension not included, match??
    else if (compareFileBaseName(file.getFileName(), fileName)) {
        System.out.println("Located file: " + file);
        files.add(file);
        exists = true;
    }
    return CONTINUE;
}
 
Example 3
Project: sstable-adaptor   File: FileUtils.java   View source code 6 votes vote down vote up
/**
 * Get the size of a directory in bytes
 * @param folder The directory for which we need size.
 * @return The size of the directory
 */
public static long folderSize(File folder)
{
    final long [] sizeArr = {0L};
    try
    {
        Files.walkFileTree(folder.toPath(), new SimpleFileVisitor<Path>()
        {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
            {
                sizeArr[0] += attrs.size();
                return FileVisitResult.CONTINUE;
            }
        });
    }
    catch (IOException e)
    {
        logger.error("Error while getting {} folder size. {}", folder, e);
    }
    return sizeArr[0];
}
 
Example 4
Project: openjdk-jdk10   File: SourcePathTest.java   View source code 6 votes vote down vote up
/**
 * This method is primarily used to give visual confirmation that a test case
 * generated files when the compilation succeeds and so generates no other output,
 * such as error messages.
 */
List<Path> showFiles(Path dir) throws IOException {
    List<Path> files = new ArrayList<>();
    Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            if (Files.isRegularFile(file)) {
                out.println("Found " + file);
                files.add(file);
            }
            return FileVisitResult.CONTINUE;
        }
    });
    return files;
}
 
Example 5
Project: LucenePlus   File: FSLuceneIndices.java   View source code 6 votes vote down vote up
protected static boolean deleteDirectoryIfExists(final Path directory) throws IOException {
    if (Files.exists(directory)) {
        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;
            }
        });
        return true;
    }
    return false;
}
 
Example 6
Project: V8LogScanner   File: LogsOperations.java   View source code 6 votes vote down vote up
public static List<Path> scanCfgPaths() {

        List<String> logcfg = Constants.V8_Dirs();

        ArrayList<Path> cfgFiles = new ArrayList<Path>();
        SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path lastName = file.getFileName();
                if (lastName != null && lastName.toString().matches("(?i)logcfg.xml"))
                    cfgFiles.add(file);
                return FileVisitResult.CONTINUE;
            }
        };

        try {
            for (String location : logcfg) {
                Files.walkFileTree(Paths.get(location), visitor);
            }
        } catch (IOException e) {
            //to do: need a feature that add log location specified by user
            ///ExcpReporting.LogError(LogsOperations.class, e);
        }
        return cfgFiles;
    }
 
Example 7
Project: hygene   File: FileMetadata.java   View source code 6 votes vote down vote up
/**
 * Computes the digest of the contents of the file this database belongs to.
 *
 * @return a digest, representing the contents of the file
 * @throws IOException in the case of an error during IO operations
 */
private String computeFileDigest() throws IOException {
    final BasicFileAttributes attr =
            Files.readAttributes(Paths.get(fileDatabase.getFileName()), BasicFileAttributes.class);

    return DigestUtils.sha512Hex(fileDatabase.getFileName() + attr.lastModifiedTime() + attr.size());
}
 
Example 8
Project: launcher-backend   File: FileUploadHelper.java   View source code 6 votes vote down vote up
/**
 * Deletes a directory recursively
 *
 * @param directory
 * @return true if deletion succeeds, false otherwise
 */
public static boolean deleteDirectory(Path directory) {
    if (directory != null) {
        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 ignored) {
            return false;
        }
    }
    return true;
}
 
Example 9
Project: AgentWorkbench   File: RecursiveFolderCopier.java   View source code 6 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
	
	// --- Check if the current folder is in the skipList ------
	if(this.skipList != null){
 	for(Path pathToSkip : skipList){
 		if(pathToSkip.equals(dir)){
 			return FileVisitResult.SKIP_SUBTREE;
 		}
 	}
	}
	
	// --- If not, create a corresponding folder in the target path ---------------
    Path targetPath = toPath.resolve(fromPath.relativize(dir));
    if(!Files.exists(targetPath)){
        Files.createDirectory(targetPath);
    }
    
    return FileVisitResult.CONTINUE;
}
 
Example 10
Project: openjdk-jdk10   File: ToolBox.java   View source code 6 votes vote down vote up
/**
 * Deletes all content of a directory (but not the directory itself).
 * @param root the directory to be cleaned
 * @throws IOException if an error occurs while cleaning the directory
 */
public void cleanDirectory(Path root) throws IOException {
    if (!Files.isDirectory(root)) {
        throw new IOException(root + " is not a directory");
    }
    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes a) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
            if (e != null) {
                throw e;
            }
            if (!dir.equals(root)) {
                Files.delete(dir);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}
 
Example 11
Project: kowalski   File: ApplicationTest.java   View source code 6 votes vote down vote up
private void deleteDirectory(Path directory) throws IOException {
	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;
		}

	});
}
 
Example 12
Project: Elasticsearch   File: LocalTranslog.java   View source code 6 votes vote down vote up
public LocalTranslog(TranslogConfig config) throws IOException {
    super(config.getShardId(), config.getIndexSettings());
    ReadWriteLock rwl = new ReentrantReadWriteLock();
    readLock = new ReleasableLock(rwl.readLock());
    writeLock = new ReleasableLock(rwl.writeLock());
    this.translogPath = config.getTranslogPath();
    // clean all files
    Files.createDirectories(this.translogPath);
    Files.walkFileTree(this.translogPath, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file,
                BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }
    });
    
    // create a new directory
    writeChannel = FileChannel.open(this.translogPath.resolve(getFileNameFromId(tmpTranslogGeneration.get())), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
    writtenOffset = 0;
}
 
Example 13
Project: mintleaf   File: FileFinder.java   View source code 6 votes vote down vote up
public List<String> list() {
    List<String> files = new ArrayList<>();
    try {
        Files.walkFileTree(Paths.get(this.path), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                Path name = regExMatch ? file.toAbsolutePath() : file.getFileName();
                if (name != null && matcher.matches(name)) {
                    files.add(file.toAbsolutePath().toString());
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        logger.error(e);
    }
    return files;
}
 
Example 14
Project: openjdk-jdk10   File: ZipFile.java   View source code 6 votes vote down vote up
public static Source get(File file, boolean toDelete) throws IOException {
    Key key = new Key(file,
                      Files.readAttributes(file.toPath(), BasicFileAttributes.class));
    Source src = null;
    synchronized (files) {
        src = files.get(key);
        if (src != null) {
            src.refs++;
            return src;
        }
    }
    src = new Source(key, toDelete);

    synchronized (files) {
        if (files.containsKey(key)) {    // someone else put in first
            src.close();                 // close the newly created one
            src = files.get(key);
            src.refs++;
            return src;
        }
        files.put(key, src);
        return src;
    }
}
 
Example 15
Project: JavaRushTasks   File: SearchFileVisitor.java   View source code 6 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    if (!attrs.isRegularFile()) return CONTINUE;

    if (partOfNameCheck && file.getFileName().toString().indexOf(this.partOfName) == -1)
        return CONTINUE;

    if (minSizeCheck && attrs.size() < minSize)
        return CONTINUE;

    if (maxSizeCheck && attrs.size() > maxSize)
        return CONTINUE;

    if (partOfContentCheck && new String(Files.readAllBytes(file)).indexOf(partOfContent) == -1)
        return CONTINUE;

    foundFiles.add(file);

    return CONTINUE;
}
 
Example 16
Project: elasticsearch_my   File: FileUtils.java   View source code 6 votes vote down vote up
private static void collectFiles(final Path dir, final String fileSuffix, final Map<String, Set<Path>> files) throws IOException {
    Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toString().endsWith(fileSuffix)) {
                String groupName = dir.relativize(file.getParent()).toString();
                Set<Path> filesSet = files.get(groupName);
                if (filesSet == null) {
                    filesSet = new HashSet<>();
                    files.put(groupName, filesSet);
                }
                filesSet.add(file);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}
 
Example 17
Project: elasticsearch_my   File: ESLoggerUsageChecker.java   View source code 6 votes vote down vote up
private static void checkLoggerUsage(Consumer<WrongLoggerUsage> wrongUsageCallback, String... classDirectories)
    throws IOException {
    for (String classDirectory : classDirectories) {
        Path root = Paths.get(classDirectory);
        if (Files.isDirectory(root) == false) {
            throw new IllegalArgumentException(root + " should be an existing directory");
        }
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (Files.isRegularFile(file) && file.getFileName().toString().endsWith(".class")) {
                    try (InputStream in = Files.newInputStream(file)) {
                        ESLoggerUsageChecker.check(wrongUsageCallback, in);
                    }
                }
                return super.visitFile(file, attrs);
            }
        });
    }
}
 
Example 18
Project: openjdk-jdk10   File: VerifyJimage.java   View source code 6 votes vote down vote up
private void compareExplodedModules(Path dir) throws IOException {
    System.out.println("comparing jimage with " + dir);

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path mdir : stream) {
            if (Files.isDirectory(mdir)) {
                pool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Files.find(mdir, Integer.MAX_VALUE, (Path p, BasicFileAttributes attr)
                                       -> !Files.isDirectory(p) &&
                                          !mdir.relativize(p).toString().startsWith("_") &&
                                          !p.getFileName().toString().equals("MANIFEST.MF"))
                                 .forEach(p -> compare(mdir, p, reader));
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    }
                });
            }
        }
    }
}
 
Example 19
Project: imagingbook-common   File: DirectoryWalker.java   View source code 6 votes vote down vote up
/**
 * Traverses the directory tree and collects all matching file names.
 * TODO: clean up exception handling.
 * 
 * @param startDir start directory
 * @throws IOException
 */
private void traverse(Path startDir) throws IOException {
	Files.walkFileTree(startDir, new SimpleFileVisitor<Path>() {
		@Override
		public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
			String pathName = file.toString();
			if (hasMatchingExtension(pathName)) {
				fileList.add(pathName);
				// System.out.println("added file " + file.toString());
			}
			return FileVisitResult.CONTINUE;
		}
		@Override
		public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
			if (e == null) {
				//System.out.println("visiting " + dir.toString());
				return FileVisitResult.CONTINUE;
			} else {
				// directory iteration failed
				throw e;
			}
		}
	});
}
 
Example 20
Project: hippo-groovy-updater   File: FileSystemWatcher.java   View source code 6 votes vote down vote up
private void registerRecursively(final Path directory) throws IOException {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(final Path visitedDirectory, final BasicFileAttributes attrs) throws IOException {
            if (!FileSystemWatcher.this.watchedFiles.matchesDirectory(visitedDirectory)) {
                return FileVisitResult.SKIP_SUBTREE;
            }


            final WatchKey key = visitedDirectory.register(watcher,
                    ENTRY_CREATE,
                    ENTRY_MODIFY,
                    ENTRY_DELETE);

            watchedPaths.put(key, visitedDirectory);

            return FileVisitResult.CONTINUE;
        }
    });
}
 
Example 21
Project: openjdk-systemtest   File: WalkFileTreeTest.java   View source code 6 votes vote down vote up
public void testWalkFileTreeMultiple() throws IOException {		
	final int ITERATIONS = 1000;
	Path newDirectory = WALKFILETREE_FILE_DIR;	
	for (int counter=0; counter< ITERATIONS; counter++) {		
		HangNotifier.ping();	
		final List<Path> visitorFiles = new LinkedList<Path>();		
		// Check that we keep returning the same set of files!
		Files.walkFileTree(newDirectory, new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) {
				if (path.toString().endsWith(".txt")) {
					visitorFiles.add(path);
				}
				return FileVisitResult.CONTINUE;
			}
		});

		if(!ReiserSpotter.getIsReiser()){
			assertEquals("Wrong number of files walked on iteration " + counter, NUMBER_OF_FILES, visitorFiles.size());
		}		
	}	
}
 
Example 22
Project: xtf   File: SourceCodeUpdater.java   View source code 6 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attr) {
	if (dir.getFileName().toString().equals(".git")) {
		return FileVisitResult.SKIP_SUBTREE;
	}
	if(onDiff == OnDiff.COPY) {
		Path relative = expected.relativize(dir);
		if (other.resolve(relative).toFile().exists()) {
			log.debug("Other has dir: {}", relative);
		} else {
			diffPresent = true;
			try {
				log.info("GitRepo does not contain dir: {}, adding", relative);
				Files.copy(dir, other.resolve(relative));
			} catch (IOException e) {
				log.error("IO happend, new build will be created", e.getMessage());
				error = true;
				return FileVisitResult.TERMINATE;
			}
		}
	}
	return FileVisitResult.CONTINUE;
}
 
Example 23
Project: guava-mock   File: MoreFilesTest.java   View source code 6 votes vote down vote up
@Override
protected void tearDown() throws Exception {
  if (tempDir != null) {
    // delete tempDir and its contents
    Files.walkFileTree(tempDir, new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        Files.deleteIfExists(file);
        return FileVisitResult.CONTINUE;
      }

      @Override
      public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        if (exc != null) {
          return FileVisitResult.TERMINATE;
        }
        Files.deleteIfExists(dir);
        return FileVisitResult.CONTINUE;
      }
    });
  }
}
 
Example 24
Project: Lagerta   File: ExportTest.java   View source code 6 votes vote down vote up
/** */
@Test(expected = IgniteException.class)
public void failIfChecksumDoesNotMatch() throws IOException {
    URI exportDirUri = folder.newFolder().toURI();
    String destination = exportDirUri.toString();
    backupInCompute(destination);

    Files.walkFileTree(Paths.get(exportDirUri), new SimpleFileVisitor<Path>() {
        @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (FileChecksumHelper.isChecksum(file)) {
                Files.write(file, "corrupted".getBytes());
            }
            return FileVisitResult.CONTINUE;
        }
    });
    restoreInCompute(destination);
}
 
Example 25
Project: elasticsearch-full   File: IndexFiles.java   View source code 6 votes vote down vote up
static void indexDocs(final IndexWriter writer, Path path) throws IOException {
    if (Files.isDirectory(path)) {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                try {
                    indexDoc(writer, file, attrs.lastModifiedTime().toMillis());
                } catch (IOException ignore) {
                    // don't index files that can't be read.
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } else {
        indexDoc(writer, path, Files.getLastModifiedTime(path).toMillis());
    }
}
 
Example 26
Project: sstable-adaptor   File: DirectorySizeCalculator.java   View source code 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
{
    if (isAcceptable(file))
        size += attrs.size();
    return FileVisitResult.CONTINUE;
}
 
Example 27
Project: openjdk-jdk10   File: ExplodedImage.java   View source code 5 votes vote down vote up
ExplodedImage(Path modulesDir) throws IOException {
    defaultFS = FileSystems.getDefault();
    String str = defaultFS.getSeparator();
    separator = str.equals("/") ? null : str;
    modulesDirAttrs = Files.readAttributes(modulesDir, BasicFileAttributes.class);
    initNodes();
}
 
Example 28
Project: openjdk-jdk10   File: ImageReader.java   View source code 5 votes vote down vote up
/**
 * Returns the file attributes of the image file.
 */
BasicFileAttributes imageFileAttributes() {
    BasicFileAttributes attrs = imageFileAttributes;
    if (attrs == null) {
        try {
            Path file = getImagePath();
            attrs = Files.readAttributes(file, BasicFileAttributes.class);
        } catch (IOException ioe) {
            throw new UncheckedIOException(ioe);
        }
        imageFileAttributes = attrs;
    }
    return attrs;
}
 
Example 29
Project: de.flapdoodle.solid   File: PathWatcher.java   View source code 5 votes vote down vote up
/**
 * Register the given directory, and all its sub-directories, with the
 * WatchService.
 */
private void walkAndRegisterDirectories(final Path start) throws IOException {
	Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
		@Override
		public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
			registerDirectory(dir);
			return FileVisitResult.CONTINUE;
		}
	});
}
 
Example 30
Project: jdk8u-jdk   File: WsImportTest.java   View source code 5 votes vote down vote up
private static void deleteGeneratedFiles() {
    Path p = Paths.get("generated");
    if (Files.exists(p)) {
        try {
            Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
                @Override
                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;
                    }
                }
            });
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
 
Example 31
Project: AgentWorkbench   File: RecursiveFolderDeleter.java   View source code 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    try {
    	Files.delete(file);
    } catch (IOException ioEx) {
    	System.err.println(RecursiveFolderDeleter.this.getClass().getSimpleName() + " - Error deleteing file: " + file.getFileName());
    	throw ioEx;
    }
    return FileVisitResult.CONTINUE;
}
 
Example 32
Project: java-tutorial   File: PrintFiles.java   View source code 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file,
                                 BasicFileAttributes attr) {
    if (attr.isSymbolicLink()) {
        System.out.format("Symbolic link: %s ", file);
    } else if (attr.isRegularFile()) {
        System.out.format("Regular file: %s ", file);
    } else {
        System.out.format("Other: %s ", file);
    }
    System.out.println("(" + attr.size() + "bytes)");
    return CONTINUE;
}
 
Example 33
Project: openjdk-jdk10   File: AbstractFileSystemProvider.java   View source code 5 votes vote down vote up
/**
 * Tests whether a file is a regular file with opaque content.
 *
 * @return  {@code true} if the file is a regular file; {@code false} if
 *          the file does not exist, is not a regular file, or it
 *          cannot be determined if the file is a regular file or not.
 */
public boolean isRegularFile(Path file) {
    try {
        return readAttributes(file, BasicFileAttributes.class).isRegularFile();
    } catch (IOException ioe) {
        return false;
    }
}
 
Example 34
Project: personium-core   File: SnapshotFileImportVisitor.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
    // Create directory
    Path relativePath = webdavRootDirInZip.relativize(dir);
    Path path = webdavRootDir.resolve(relativePath.toString());
    Files.createDirectories(path);
    return FileVisitResult.CONTINUE;
}
 
Example 35
Project: powsybl-core   File: LocalAppStorage.java   View source code 5 votes vote down vote up
private NodeInfo getNodeInfo(Path path) {
    BasicFileAttributes attr;
    try {
        attr = Files.readAttributes(path, BasicFileAttributes.class);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    LocalFile file = scanFile(path, true);
    if (file != null) {
        return new NodeInfo(path.toString(),
                            file.getName(),
                            file.getPseudoClass(),
                            file.getDescription(),
                            attr.creationTime().toMillis(),
                            attr.lastModifiedTime().toMillis(),
                            DEFAULT_VERSION,
                            file.getGenericMetadata());
    } else {
        LocalFolder folder = scanFolder(path, true);
        if (folder != null) {
            return new NodeInfo(path.toString(),
                                folder.getName(),
                                Folder.PSEUDO_CLASS,
                                "",
                                attr.creationTime().toMillis(),
                                attr.lastModifiedTime().toMillis(),
                                DEFAULT_VERSION,
                                new NodeGenericMetadata());
        } else {
            throw new AssertionError();
        }
    }
}
 
Example 36
Project: artifactory-resource   File: DirectoryScanner.java   View source code 5 votes vote down vote up
private BiPredicate<Path, BasicFileAttributes> getFilter(Directory root,
		List<String> include, List<String> exclude) {
	PathFilter filter = new PathFilter(include, exclude);
	String rootPath = StringUtils.cleanPath(root.getFile().getPath());
	return (path, fileAttributes) -> {
		if (!path.toFile().isFile()) {
			return false;
		}
		String relativePath = StringUtils.cleanPath(path.toString())
				.substring(rootPath.length() + 1);
		return filter.isMatch(relativePath);
	};
}
 
Example 37
Project: OpenJSharp   File: SimpleFileVisitor.java   View source code 5 votes vote down vote up
/**
 * Invoked for a directory before entries in the directory are visited.
 *
 * <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE
 * CONTINUE}.
 */
@Override
public FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs)
    throws IOException
{
    Objects.requireNonNull(dir);
    Objects.requireNonNull(attrs);
    return FileVisitResult.CONTINUE;
}
 
Example 38
Project: Re-Collector   File: GlobPathSet.java   View source code 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
    if (matcher.matches(file)) {
        // TODO needs to be an absolute path because otherwise the FileObserver does weird things. Investigate what's wrong with it.
        matchedPaths.add(file.toAbsolutePath());
    }

    return FileVisitResult.CONTINUE;
}
 
Example 39
Project: GravSupport   File: CopyFileVisitor.java   View source code 5 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(final Path dir,
                                         final BasicFileAttributes attrs) throws IOException {
    if (sourcePath == null) {
        sourcePath = dir;
    } else {
    Files.createDirectories(targetPath.resolve(sourcePath
                .relativize(dir)));
    }
    return FileVisitResult.CONTINUE;
}
 
Example 40
Project: fuse-nio-adapter   File: ReadOnlyDirectoryHandler.java   View source code 5 votes vote down vote up
public int getattr(Path path, FileStat stat) {
	stat.st_mode.set(FileStat.S_IFDIR | 0555);
	long nlinks;
	try {
		BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
		attrUtil.copyBasicFileAttributesFromNioToFuse(attr, stat);
		nlinks = 2 + countSubDirs(path);
	} catch (IOException e) {
		nlinks = 2;
	}
	stat.st_nlink.set(nlinks);
	return 0;
}