Search in sources :

Example 51 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project jabref by JabRef.

the class CiteKeyBasedFileFinder method findFilesByExtension.

/**
     * Returns a list of all files in the given directories which have one of the given extension.
     */
public Set<Path> findFilesByExtension(List<Path> directories, List<String> extensions) {
    Objects.requireNonNull(extensions, "Extensions must not be null!");
    BiPredicate<Path, BasicFileAttributes> isFileWithCorrectExtension = (path, attributes) -> !Files.isDirectory(path) && extensions.contains(FileHelper.getFileExtension(path).orElse(""));
    Set<Path> result = new HashSet<>();
    for (Path directory : directories) {
        try (Stream<Path> files = Files.find(directory, Integer.MAX_VALUE, isFileWithCorrectExtension)) {
            result.addAll(files.collect(Collectors.toSet()));
        } catch (IOException e) {
            LOGGER.error("Problem in finding files", e);
        }
    }
    return result;
}
Also used : Files(java.nio.file.Files) BibEntry(org.jabref.model.entry.BibEntry) Set(java.util.Set) IOException(java.io.IOException) HashMap(java.util.HashMap) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) FileHelper(org.jabref.model.util.FileHelper) HashSet(java.util.HashSet) Objects(java.util.Objects) BiPredicate(java.util.function.BiPredicate) List(java.util.List) Stream(java.util.stream.Stream) Map(java.util.Map) Optional(java.util.Optional) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) Path(java.nio.file.Path) Path(java.nio.file.Path) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) HashSet(java.util.HashSet)

Example 52 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project bnd by bndtools.

the class IO method copy.

public static Path copy(Path src, Path tgt) throws IOException {
    final Path source = src.toAbsolutePath();
    final Path target = tgt.toAbsolutePath();
    if (Files.isRegularFile(source)) {
        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
        return tgt;
    }
    if (Files.isDirectory(source)) {
        if (Files.notExists(target)) {
            mkdirs(target);
        }
        if (!Files.isDirectory(target))
            throw new IllegalArgumentException("target directory for a directory must be a directory: " + target);
        if (target.startsWith(source))
            throw new IllegalArgumentException("target directory can not be child of source directory.");
        Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new FileVisitor<Path>() {

            final FileTime now = FileTime.fromMillis(System.currentTimeMillis());

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Path targetdir = target.resolve(source.relativize(dir));
                try {
                    Files.copy(dir, targetdir);
                } catch (FileAlreadyExistsException e) {
                    if (!Files.isDirectory(targetdir))
                        throw e;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path targetFile = target.resolve(source.relativize(file));
                Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING);
                Files.setLastModifiedTime(targetFile, now);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                if (exc != null) {
                    // directory iteration failed
                    throw exc;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (exc != null) {
                    throw exc;
                }
                return FileVisitResult.CONTINUE;
            }
        });
        return tgt;
    }
    throw new FileNotFoundException("During copy: " + source.toString());
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileNotFoundException(java.io.FileNotFoundException) FileTime(java.nio.file.attribute.FileTime) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 53 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project bnd by bndtools.

the class IO method createSymbolicLinkOrCopy.

/**
	 * Creates a symbolic link from {@code link} to the {@code target}, or
	 * copies {@code target} to {@code link} if running on Windows.
	 * <p>
	 * Creating symbolic links on Windows requires administrator permissions, so
	 * copying is a safer fallback. Copy only happens if timestamp and and file
	 * length are different than target
	 *
	 * @param link the location of the symbolic link, or destination of the
	 *            copy.
	 * @param target the source of the symbolic link, or source of the copy.
	 * @return {@code true} if the operation succeeds, {@code false} otherwise.
	 */
public static boolean createSymbolicLinkOrCopy(Path link, Path target) {
    try {
        if (isWindows || !createSymbolicLink(link, target)) {
            // only copy if target length and timestamp differ
            BasicFileAttributes targetAttrs = Files.readAttributes(target, BasicFileAttributes.class);
            try {
                BasicFileAttributes linkAttrs = Files.readAttributes(link, BasicFileAttributes.class);
                if (targetAttrs.lastModifiedTime().equals(linkAttrs.lastModifiedTime()) && targetAttrs.size() == linkAttrs.size()) {
                    return true;
                }
            } catch (IOException e) {
            // link does not exist
            }
            copy(target, link);
            Files.setLastModifiedTime(link, targetAttrs.lastModifiedTime());
        }
        return true;
    } catch (Exception ignore) {
    // ignore
    }
    return false;
}
Also used : IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileNotFoundException(java.io.FileNotFoundException)

Example 54 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project Gargoyle by callakrsos.

the class FilePropertiesComposite method apply.

/**********************************************************************************************/
/* 이벤트 처리항목 기술 */
// TODO Auto-generated constructor stub
/**********************************************************************************************/
/**********************************************************************************************/
/*
	 * (non-Javadoc)
	 *
	 * @see java.util.function.Function#apply(java.lang.Object)
	 */
@Override
public List<Map<String, Object>> apply(File file) {
    ObservableList<Map<String, Object>> items = FXCollections.observableArrayList();
    Long totalSpace = this.file.getTotalSpace();
    Long usableSpace = this.file.getUsableSpace();
    Long freeSpace = this.file.getFreeSpace();
    Long fileSize = this.file.length();
    String name = this.file.getName();
    boolean isExecutable = this.file.canExecute();
    boolean isWriable = this.file.canWrite();
    boolean isReadable = this.file.canRead();
    boolean hidden = this.file.isHidden();
    String path = this.file.getAbsolutePath();
    int totalCnt = 0;
    int fileCnt = 0;
    int dirCnt = 0;
    if (file.isDirectory()) {
        for (File f : file.listFiles()) {
            if (f.isFile())
                fileCnt++;
            else if (f.isDirectory())
                dirCnt++;
            totalCnt++;
        }
    }
    //grid
    items.add(toMap("name", name));
    items.add(toMap("path", path));
    items.add(toMap("totalSpace(byte)", toNumberString(totalSpace)));
    items.add(toMap("usableSpace(byte)", toNumberString(usableSpace)));
    items.add(toMap("freeSpace(byte)", toNumberString(freeSpace)));
    items.add(toMap("fileSize(byte)", toNumberString(fileSize)));
    items.add(toMap("isExecutable", isExecutable));
    items.add(toMap("isWriable", isWriable));
    items.add(toMap("isReadable", isReadable));
    items.add(toMap("hidden", hidden));
    //chart
    ObservableList<Map<String, Object>> sizeItems = FXCollections.observableArrayList();
    sizeItems.add(toMap("totalSpace(byte)", totalSpace.toString()));
    sizeItems.add(toMap("usableSpace(byte)", usableSpace.toString()));
    sizeItems.add(toMap("freeSpace(byte)", freeSpace.toString()));
    sizeItems.add(toMap("fileSize(byte)", fileSize.toString()));
    this.picChart.setData(ChartCreator.convertNewData(totalSpace, sizeItems));
    try {
        BasicFileAttributes readAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
        FileTime lastAccessTime = readAttributes.lastAccessTime();
        FileTime creationTime = readAttributes.creationTime();
        FileTime lastModifiedTime = readAttributes.lastModifiedTime();
        boolean symbolicLink = readAttributes.isSymbolicLink();
        items.add(toMap("creationTime", toDate(creationTime.toMillis())));
        items.add(toMap("lastAccessTime", toDate(lastAccessTime.toMillis())));
        items.add(toMap("lastModifiedTime", toDate(lastModifiedTime.toMillis())));
        items.add(toMap("symbolicLink", symbolicLink));
    } catch (IOException e) {
        e.printStackTrace();
    }
    items.add(toMap("all file count", totalCnt));
    items.add(toMap("only file count ", fileCnt));
    items.add(toMap("only dir count", dirCnt));
    return items;
}
Also used : FileTime(java.nio.file.attribute.FileTime) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 55 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project cdap by caskdata.

the class SparkPackageUtils method getSpark1AssemblyJar.

/**
   * Locates the spark-assembly jar from the local file system for Spark1.
   *
   * @param sparkLibrary file path to the spark-assembly jar in the local file system
   * @param sparkHome file path to the spark home.
   *
   * @return the spark-assembly jar location
   * @throws IllegalStateException if cannot locate the spark assembly jar
   */
private static File getSpark1AssemblyJar(@Nullable String sparkLibrary, String sparkHome) {
    if (sparkLibrary != null) {
        return new File(sparkLibrary);
    }
    // Look for spark-assembly.jar symlink
    Path assemblyJar = Paths.get(sparkHome, "lib", "spark-assembly.jar");
    if (Files.isSymbolicLink(assemblyJar)) {
        return assemblyJar.toFile();
    }
    // No symbolic link exists. Search for spark-assembly*.jar in the lib directory
    final List<Path> jar = new ArrayList<>(1);
    Path sparkLib = Paths.get(sparkHome, "lib");
    final PathMatcher pathMatcher = sparkLib.getFileSystem().getPathMatcher("glob:spark-assembly*.jar");
    try {
        Files.walkFileTree(sparkLib, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                // Take the first file match
                if (attrs.isRegularFile() && pathMatcher.matches(file.getFileName())) {
                    jar.add(file);
                    return FileVisitResult.TERMINATE;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                // Ignore error
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        // Just log, don't throw.
        // If we already located the Spark Assembly jar during visiting, we can still use the jar.
        LOG.warn("Exception raised while inspecting {}", sparkLib, e);
    }
    Preconditions.checkState(!jar.isEmpty(), "Failed to locate Spark library from %s", sparkHome);
    assemblyJar = jar.get(0);
    LOG.debug("Located Spark Assembly JAR in {}", assemblyJar);
    return assemblyJar.toFile();
}
Also used : Path(java.nio.file.Path) PathMatcher(java.nio.file.PathMatcher) ArrayList(java.util.ArrayList) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) File(java.io.File) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)119 Path (java.nio.file.Path)93 IOException (java.io.IOException)87 FileVisitResult (java.nio.file.FileVisitResult)66 File (java.io.File)18 Test (org.junit.Test)13 SimpleFileVisitor (java.nio.file.SimpleFileVisitor)11 ArrayList (java.util.ArrayList)11 HashSet (java.util.HashSet)8 FileNotFoundException (java.io.FileNotFoundException)7 InputStream (java.io.InputStream)6 HashMap (java.util.HashMap)6 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)5 BasicFileAttributeView (java.nio.file.attribute.BasicFileAttributeView)5 SourcePath (com.facebook.buck.rules.SourcePath)4 ImmutableList (com.google.common.collect.ImmutableList)4 OutputStream (java.io.OutputStream)4 URI (java.net.URI)4 FileSystem (java.nio.file.FileSystem)4 FileVisitor (java.nio.file.FileVisitor)4