Java Code Examples for java.nio.file.attribute.BasicFileAttributes.isDirectory()

The following are Jave code examples for showing how to use isDirectory() of the java.nio.file.attribute.BasicFileAttributes class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: guava-mock   File: MoreFiles.java   View Source Code Vote up 6 votes
@Override
public Optional<Long> sizeIfKnown() {
  BasicFileAttributes attrs;
  try {
    attrs = readAttributes();
  } catch (IOException e) {
    // Failed to get attributes; we don't know the size.
    return Optional.absent();
  }

  // Don't return a size for directories or symbolic links; their sizes are implementation
  // specific and they can't be read as bytes using the read methods anyway.
  if (attrs.isDirectory() || attrs.isSymbolicLink()) {
    return Optional.absent();
  }

  return Optional.of(attrs.size());
}
 
Example 2
Project: openjdk-jdk10   File: Resources.java   View Source Code Vote up 6 votes
/**
 * Returns a file path to a resource in a file tree. If the resource
 * name has a trailing "/" then the file path will locate a directory.
 * Returns {@code null} if the resource does not map to a file in the
 * tree file.
 */
public static Path toFilePath(Path dir, String name) throws IOException {
    boolean expectDirectory = name.endsWith("/");
    if (expectDirectory) {
        name = name.substring(0, name.length() - 1);  // drop trailing "/"
    }
    Path path = toSafeFilePath(dir.getFileSystem(), name);
    if (path != null) {
        Path file = dir.resolve(path);
        try {
            BasicFileAttributes attrs;
            attrs = Files.readAttributes(file, BasicFileAttributes.class);
            if (attrs.isDirectory()
                || (!attrs.isDirectory() && !expectDirectory))
                return file;
        } catch (NoSuchFileException ignore) { }
    }
    return null;
}
 
Example 3
Project: googles-monorepo-demo   File: MoreFiles.java   View Source Code Vote up 6 votes
@Override
public Optional<Long> sizeIfKnown() {
  BasicFileAttributes attrs;
  try {
    attrs = readAttributes();
  } catch (IOException e) {
    // Failed to get attributes; we don't know the size.
    return Optional.absent();
  }

  // Don't return a size for directories or symbolic links; their sizes are implementation
  // specific and they can't be read as bytes using the read methods anyway.
  if (attrs.isDirectory() || attrs.isSymbolicLink()) {
    return Optional.absent();
  }

  return Optional.of(attrs.size());
}
 
Example 4
Project: elasticsearch_my   File: FileWatcher.java   View Source Code Vote up 5 votes
private void init(boolean initial) throws IOException {
    exists = Files.exists(file);
    if (exists) {
        BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);
        isDirectory = attributes.isDirectory();
        if (isDirectory) {
            onDirectoryCreated(initial);
        } else {
            length = attributes.size();
            lastModified = attributes.lastModifiedTime().toMillis();
            onFileCreated(initial);
        }
    }
}
 
Example 5
Project: truevfs   File: FileNode.java   View Source Code Vote up 5 votes
@Override
public final BitField<Type> getTypes() {
    try {
        final BasicFileAttributes attr = readBasicFileAttributes();
        if      (attr.isRegularFile())  return FILE_TYPE;
        else if (attr.isDirectory())    return DIRECTORY_TYPE;
        else if (attr.isSymbolicLink()) return SYMLINK_TYPE;
        else if (attr.isOther())        return SPECIAL_TYPE;
    } catch (IOException ignore) {
        // This doesn't exist or may be inaccessible. In either case...
    }
    return NO_TYPES;
}
 
Example 6
Project: guava-mock   File: MoreFiles.java   View Source Code Vote up 5 votes
@Override
public long size() throws IOException {
  BasicFileAttributes attrs = readAttributes();

  // Don't return a size for directories or symbolic links; their sizes are implementation
  // specific and they can't be read as bytes using the read methods anyway.
  if (attrs.isDirectory()) {
    throw new IOException("can't read: is a directory");
  } else if (attrs.isSymbolicLink()) {
    throw new IOException("can't read: is a symbolic link");
  }

  return attrs.size();
}
 
Example 7
Project: Elasticsearch   File: FileWatcher.java   View Source Code Vote up 5 votes
private void init(boolean initial) throws IOException {
    exists = Files.exists(file);
    if (exists) {
        BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);
        isDirectory = attributes.isDirectory();
        if (isDirectory) {
            onDirectoryCreated(initial);
        } else {
            length = attributes.size();
            lastModified = attributes.lastModifiedTime().toMillis();
            onFileCreated(initial);
        }
    }
}
 
Example 8
Project: openjdk-jdk10   File: LauncherHelper.java   View Source Code Vote up 5 votes
/**
 * Scan an element on a module path. The element is a directory
 * of modules, an exploded module, or a JAR file.
 */
void scan(Path entry) {
    BasicFileAttributes attrs;
    try {
        attrs = Files.readAttributes(entry, BasicFileAttributes.class);
    } catch (NoSuchFileException ignore) {
        return;
    } catch (IOException ioe) {
        ostream.println(entry + " " + ioe);
        errorFound = true;
        return;
    }

    String fn = entry.getFileName().toString();
    if (attrs.isRegularFile() && fn.endsWith(".jar")) {
        // JAR file, explicit or automatic module
        scanModule(entry).ifPresent(this::process);
    } else if (attrs.isDirectory()) {
        Path mi = entry.resolve(MODULE_INFO);
        if (Files.exists(mi)) {
            // exploded module
            scanModule(entry).ifPresent(this::process);
        } else {
            // directory of modules
            scanDirectory(entry);
        }
    }
}
 
Example 9
Project: openjdk-jdk10   File: PollingWatchService.java   View Source Code Vote up 5 votes
private PollingWatchKey doPrivilegedRegister(Path path,
                                             Set<? extends WatchEvent.Kind<?>> events,
                                             int sensitivityInSeconds)
    throws IOException
{
    // check file is a directory and get its file key if possible
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
    if (!attrs.isDirectory()) {
        throw new NotDirectoryException(path.toString());
    }
    Object fileKey = attrs.fileKey();
    if (fileKey == null)
        throw new AssertionError("File keys must be supported");

    // grab close lock to ensure that watch service cannot be closed
    synchronized (closeLock()) {
        if (!isOpen())
            throw new ClosedWatchServiceException();

        PollingWatchKey watchKey;
        synchronized (map) {
            watchKey = map.get(fileKey);
            if (watchKey == null) {
                // new registration
                watchKey = new PollingWatchKey(path, this, fileKey);
                map.put(fileKey, watchKey);
            } else {
                // update to existing registration
                watchKey.disable();
            }
        }
        watchKey.enable(events, sensitivityInSeconds);
        return watchKey;
    }

}
 
Example 10
Project: googles-monorepo-demo   File: MoreFiles.java   View Source Code Vote up 5 votes
@Override
public long size() throws IOException {
  BasicFileAttributes attrs = readAttributes();

  // Don't return a size for directories or symbolic links; their sizes are implementation
  // specific and they can't be read as bytes using the read methods anyway.
  if (attrs.isDirectory()) {
    throw new IOException("can't read: is a directory");
  } else if (attrs.isSymbolicLink()) {
    throw new IOException("can't read: is a symbolic link");
  }

  return attrs.size();
}
 
Example 11
Project: elasticsearch_my   File: FileWatcher.java   View Source Code Vote up 4 votes
public void checkAndNotify() throws IOException {
    boolean prevExists = exists;
    boolean prevIsDirectory = isDirectory;
    long prevLength = length;
    long prevLastModified = lastModified;

    exists = Files.exists(file);
    // TODO we might use the new NIO2 API to get real notification?
    if (exists) {
        BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);
        isDirectory = attributes.isDirectory();
        if (isDirectory) {
            length = 0;
            lastModified = 0;
        } else {
            length = attributes.size();
            lastModified = attributes.lastModifiedTime().toMillis();
        }
    } else {
        isDirectory = false;
        length = 0;
        lastModified = 0;
    }

    // Perform notifications and update children for the current file
    if (prevExists) {
        if (exists) {
            if (isDirectory) {
                if (prevIsDirectory) {
                    // Remained a directory
                    updateChildren();
                } else {
                    // File replaced by directory
                    onFileDeleted();
                    onDirectoryCreated(false);
                }
            } else {
                if (prevIsDirectory) {
                    // Directory replaced by file
                    onDirectoryDeleted();
                    onFileCreated(false);
                } else {
                    // Remained file
                    if (prevLastModified != lastModified || prevLength != length) {
                        onFileChanged();
                    }
                }
            }
        } else {
            // Deleted
            if (prevIsDirectory) {
                onDirectoryDeleted();
            } else {
                onFileDeleted();
            }
        }
    } else {
        // Created
        if (exists) {
            if (isDirectory) {
                onDirectoryCreated(false);
            } else {
                onFileCreated(false);
            }
        }
    }

}
 
Example 12
Project: Elasticsearch   File: FileWatcher.java   View Source Code Vote up 4 votes
public void checkAndNotify() throws IOException {
    boolean prevExists = exists;
    boolean prevIsDirectory = isDirectory;
    long prevLength = length;
    long prevLastModified = lastModified;

    exists = Files.exists(file);
    // TODO we might use the new NIO2 API to get real notification?
    if (exists) {
        BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);
        isDirectory = attributes.isDirectory();
        if (isDirectory) {
            length = 0;
            lastModified = 0;
        } else {
            length = attributes.size();
            lastModified = attributes.lastModifiedTime().toMillis();
        }
    } else {
        isDirectory = false;
        length = 0;
        lastModified = 0;
    }

    // Perform notifications and update children for the current file
    if (prevExists) {
        if (exists) {
            if (isDirectory) {
                if (prevIsDirectory) {
                    // Remained a directory
                    updateChildren();
                } else {
                    // File replaced by directory
                    onFileDeleted();
                    onDirectoryCreated(false);
                }
            } else {
                if (prevIsDirectory) {
                    // Directory replaced by file
                    onDirectoryDeleted();
                    onFileCreated(false);
                } else {
                    // Remained file
                    if (prevLastModified != lastModified || prevLength != length) {
                        onFileChanged();
                    }
                }
            }
        } else {
            // Deleted
            if (prevIsDirectory) {
                onDirectoryDeleted();
            } else {
                onFileDeleted();
            }
        }
    } else {
        // Created
        if (exists) {
            if (isDirectory) {
                onDirectoryCreated(false);
            } else {
                onFileCreated(false);
            }
        }
    }

}
 
Example 13
Project: Elasticsearch   File: HttpServer.java   View Source Code Vote up 4 votes
void handlePluginSite(HttpRequest request, HttpChannel channel) throws IOException {
    if (disableSites) {
        channel.sendResponse(new BytesRestResponse(FORBIDDEN));
        return;
    }
    if (request.method() == RestRequest.Method.OPTIONS) {
        // when we have OPTIONS request, simply send OK by default (with the Access Control Origin header which gets automatically added)
        channel.sendResponse(new BytesRestResponse(OK));
        return;
    }
    if (request.method() != RestRequest.Method.GET) {
        channel.sendResponse(new BytesRestResponse(FORBIDDEN));
        return;
    }
    // TODO for a "/_plugin" endpoint, we should have a page that lists all the plugins?

    String path = request.rawPath().substring("/_plugin/".length());
    int i1 = path.indexOf('/');
    String pluginName;
    String sitePath;
    if (i1 == -1) {
        pluginName = path;
        sitePath = null;
        // If a trailing / is missing, we redirect to the right page #2654
        String redirectUrl = request.rawPath() + "/";
        BytesRestResponse restResponse = new BytesRestResponse(RestStatus.MOVED_PERMANENTLY, "text/html", "<head><meta http-equiv=\"refresh\" content=\"0; URL=" + redirectUrl + "\"></head>");
        restResponse.addHeader("Location", redirectUrl);
        channel.sendResponse(restResponse);
        return;
    } else {
        pluginName = path.substring(0, i1);
        sitePath = path.substring(i1 + 1);
    }

    // we default to index.html, or what the plugin provides (as a unix-style path)
    // this is a relative path under _site configured by the plugin.
    if (sitePath.length() == 0) {
        sitePath = "index.html";
    } else {
        // remove extraneous leading slashes, its not an absolute path.
        while (sitePath.length() > 0 && sitePath.charAt(0) == '/') {
            sitePath = sitePath.substring(1);
        }
    }
    final Path siteFile = environment.pluginsFile().resolve(pluginName).resolve("_site");

    final String separator = siteFile.getFileSystem().getSeparator();
    // Convert file separators.
    sitePath = sitePath.replace("/", separator);
    
    Path file = siteFile.resolve(sitePath);

    // return not found instead of forbidden to prevent malicious requests to find out if files exist or dont exist
    if (!Files.exists(file) || FileSystemUtils.isHidden(file) || !file.toAbsolutePath().normalize().startsWith(siteFile.toAbsolutePath().normalize())) {
        channel.sendResponse(new BytesRestResponse(NOT_FOUND));
        return;
    }

    BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);
    if (!attributes.isRegularFile()) {
        // If it's not a dir, we send a 403
        if (!attributes.isDirectory()) {
            channel.sendResponse(new BytesRestResponse(FORBIDDEN));
            return;
        }
        // We don't serve dir but if index.html exists in dir we should serve it
        file = file.resolve("index.html");
        if (!Files.exists(file) || FileSystemUtils.isHidden(file) || !Files.isRegularFile(file)) {
            channel.sendResponse(new BytesRestResponse(FORBIDDEN));
            return;
        }
    }

    try {
        byte[] data = Files.readAllBytes(file);
        channel.sendResponse(new BytesRestResponse(OK, guessMimeType(sitePath), data));
    } catch (IOException e) {
        channel.sendResponse(new BytesRestResponse(INTERNAL_SERVER_ERROR));
    }
}
 
Example 14
Project: OpenJSharp   File: JavacPathFileManager.java   View Source Code Vote up 4 votes
private static boolean isDirectory(Path path) throws IOException {
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
    return attrs.isDirectory();
}
 
Example 15
Project: openjdk-jdk10   File: ModulePath.java   View Source Code Vote up 4 votes
/**
 * Reads a packaged or exploded module, returning a {@code ModuleReference}
 * to the module. Returns {@code null} if the entry is not recognized.
 *
 * @throws IOException if an I/O error occurs
 * @throws FindException if an error occurs parsing its module descriptor
 */
private ModuleReference readModule(Path entry, BasicFileAttributes attrs)
    throws IOException
{
    try {

        // exploded module
        if (attrs.isDirectory()) {
            return readExplodedModule(entry); // may return null
        }

        // JAR or JMOD file
        if (attrs.isRegularFile()) {
            String fn = entry.getFileName().toString();
            boolean isDefaultFileSystem = isDefaultFileSystem(entry);

            // JAR file
            if (fn.endsWith(".jar")) {
                if (isDefaultFileSystem) {
                    return readJar(entry);
                } else {
                    // the JAR file is in a custom file system so
                    // need to copy it to the local file system
                    Path tmpdir = Files.createTempDirectory("mlib");
                    Path target = Files.copy(entry, tmpdir.resolve(fn));
                    return readJar(target);
                }
            }

            // JMOD file
            if (isDefaultFileSystem && isLinkPhase && fn.endsWith(".jmod")) {
                return readJMod(entry);
            }
        }

        return null;

    } catch (InvalidModuleDescriptorException e) {
        throw new FindException("Error reading module: " + entry, e);
    }
}