下面列出了java.nio.file.attribute.BasicFileAttributes#isDirectory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static List<Path> discoverContexts(Path root) {
List<Path> jars = new ArrayList<>();
SimpleFileVisitor visitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
if (!attributes.isDirectory()) {
if (file.toString().endsWith(".js")) {
jars.add(file);
}
}
return FileVisitResult.CONTINUE;
}
};
try {
Files.walkFileTree(root, visitor);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
return jars;
}
public static void listDir(Path path, int depth) throws Exception {
BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
// if directory, list the files, and traverse down iside each of those
if(attr.isDirectory()) {
DirectoryStream<Path> paths = Files.newDirectoryStream(path);
System.out.println(spacesForDepth(depth) + " > " + path.getFileName());
for(Path tempPath: paths) {
listDir(tempPath, depth + 1);
}
} else {
System.out.println(spacesForDepth(depth) + " -- " + path.getFileName());
}
}
private static Response createDirectory(MCRPath mcrPath) {
try {
BasicFileAttributes directoryAttrs = Files.readAttributes(mcrPath, BasicFileAttributes.class);
if (!directoryAttrs.isDirectory()) {
throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_CREATE_DIRECTORY_ON_FILE)
.withMessage("Could not create directory " + mcrPath + ". A file allready exist!")
.toException();
}
return Response.noContent().build();
} catch (IOException e) {
//does not exist
LogManager.getLogger().info("Creating directory: {}", mcrPath);
try {
doWithinTransaction(() -> Files.createDirectory(mcrPath));
} catch (IOException e2) {
throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_CREATE_DIRECTORY)
.withMessage("Could not create directory " + mcrPath + ".")
.withDetail(e.getMessage())
.withCause(e)
.toException();
}
return Response.status(Response.Status.CREATED).build();
}
}
public void iterateOverMFileCollection(Visitor visit) throws IOException {
if (debug)
System.out.printf(" iterateOverMFileCollection %s ", collectionDir);
int count = 0;
try (DirectoryStream<Path> ds = Files.newDirectoryStream(collectionDir, new MyStreamFilter())) {
for (Path p : ds) {
try {
BasicFileAttributes attr = Files.readAttributes(p, BasicFileAttributes.class);
if (!attr.isDirectory())
visit.consume(new MFileOS7(p));
if (debug)
System.out.printf("%d ", count++);
} catch (IOException ioe) {
// catch error and skip file
logger.error("Failed to read attributes from file found in Files.newDirectoryStream ", ioe);
}
}
}
if (debug)
System.out.printf("%d%n", count);
}
public static void listDirAndFollow(Path path, int depth) throws Exception{
BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
if(path.endsWith(".git")) {
return;
}
// case for directory
if(attributes.isDirectory()) {
depth++;
// print for each directory
System.out.println(getSpacesForDepth(depth) + ">" + path.getFileName());
// now call for each child:
DirectoryStream<Path> paths = Files.newDirectoryStream(path);
for(Path tmpPath: paths) {
listDirAndFollow(tmpPath, depth);
}
} else {
// Case for a file
System.out.println(getSpacesForDepth(depth) + " -->" + path.getFileName());
}
}
private FileVisitResult visitPath(Path p) throws IOException {
BasicFileAttributes attrs;
try {
attrs = getAttributes(p);
ensureNoLoops(p, attrs);
} catch (IOException ioe) {
return visitor.visitFileFailed(p, ioe);
}
if (attrs.isDirectory()) {
FileVisitResult result = visitor.preVisitDirectory(p, attrs);
if (result == FileVisitResult.CONTINUE) {
state.add(new DirWalkState(p, attrs, false));
}
return result;
} else {
return visitor.visitFile(p, attrs);
}
}
/**
* 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);
}
}
}
/**
* Delete directory recursively.
*
* @param f Directory.
* @param deleteIfExists Ignore delete errors if the file doesn't exist.
* @return {@code true} if successful.
*/
private boolean deleteRecursive(File f, boolean deleteIfExists) {
BasicFileAttributes attrs;
try {
attrs = Files.readAttributes(f.toPath(), BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
}
catch (IOException ignore) {
return deleteIfExists && !f.exists();
}
if (!attrs.isDirectory() || attrs.isSymbolicLink())
return f.delete() || (deleteIfExists && !f.exists());
File[] entries = f.listFiles();
if (entries != null) {
for (File entry : entries) {
boolean res = deleteRecursive(entry, true);
if (!res)
return false;
}
}
return f.delete() || (deleteIfExists && !f.exists());
}
@Override
public DirectoryList transform(DirectoryListKey key, ComputationEnvironment env)
throws Exception {
ImmutableCollection<Path> contents = fileSystemView.getDirectoryContents(key.getPath());
ImmutableSortedSet.Builder<Path> filesBuilder =
new ImmutableSortedSet.Builder<>(Comparator.naturalOrder());
ImmutableSortedSet.Builder<Path> dirsBuilder =
new ImmutableSortedSet.Builder<>(Comparator.naturalOrder());
ImmutableSortedSet.Builder<Path> symlinksBuilder =
new ImmutableSortedSet.Builder<>(Comparator.naturalOrder());
for (Path p : contents) {
BasicFileAttributes attrs =
fileSystemView.readAttributes(p, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
if (attrs.isDirectory()) {
dirsBuilder.add(p);
continue;
}
if (attrs.isRegularFile()) {
filesBuilder.add(p);
continue;
}
if (attrs.isSymbolicLink()) {
symlinksBuilder.add(p);
continue;
}
}
return ImmutableDirectoryList.of(
filesBuilder.build(), dirsBuilder.build(), symlinksBuilder.build());
}
public static FileType fromAttribute(BasicFileAttributes attrs) {
if (attrs.isRegularFile()) {
return file;
}
if (attrs.isDirectory()) {
return directory;
}
if (attrs.isSymbolicLink()) {
return link;
}
return other;
}
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;
}
}
private long getTotalSize(Path path) throws IOException {
BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
long size = attributes.size();
if (attributes.isDirectory()) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path p : stream) {
size += getTotalSize(p);
}
}
}
return size;
}
private static boolean isDirectory(Path path) throws IOException {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
return attrs.isDirectory();
}
private static boolean isDirectory(Path path) throws IOException {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
return attrs.isDirectory();
}
@PUT
@Consumes(MediaType.WILDCARD)
@Operation(summary = "Creates directory or file. Parent must exists.",
responses = {
@ApiResponse(responseCode = "204", description = "if directory already exists or while was updated"),
@ApiResponse(responseCode = "201", description = "if directory or file was created"),
@ApiResponse(responseCode = "400",
description = "if directory overwrites file or vice versa; content length is too big"),
},
tags = MCRRestUtils.TAG_MYCORE_FILE)
public Response createFileOrDirectory(InputStream contents) {
MCRPath mcrPath = MCRPath.getPath(derid.toString(), path);
if (mcrPath.getNameCount() > 1) {
MCRPath parentDirectory = mcrPath.getParent();
try {
BasicFileAttributes parentAttrs = Files.readAttributes(parentDirectory, BasicFileAttributes.class);
if (!parentAttrs.isDirectory()) {
throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_NOT_DIRECTORY)
.withMessage(parentDirectory + " is not a directory.")
.toException();
}
} catch (IOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_NOT_FOUND)
.withMessage("Could not find directory " + parentDirectory + ".")
.withDetail(e.getMessage())
.withCause(e)
.toException();
}
}
if (isFile()) {
long maxSize = getUploadMaxSize();
String contentLength = request.getHeaderString(HttpHeaders.CONTENT_LENGTH);
if (contentLength != null && Long.parseLong(contentLength) > maxSize) {
throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_SIZE)
.withMessage("Maximum file size (" + maxSize + " bytes) exceeded.")
.withDetail(contentLength)
.toException();
}
return updateOrCreateFile(contents, mcrPath);
} else {
//is directory
return createDirectory(mcrPath);
}
}
private static boolean isDirectory(Path path) throws IOException {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
return attrs.isDirectory();
}
private static boolean isDirectory(Path path) throws IOException {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
return attrs.isDirectory();
}
/**
* Returns the status of a file. See {@link Path#stat(Symlinks)} for
* specification.
*
* <p>The default implementation of this method is a "lazy" one, based on
* other accessor methods such as {@link #isFile}, etc. Subclasses may provide
* more efficient specializations. However, we still try to follow Unix-like
* semantics of failing fast in case of non-existent files (or in case of
* permission issues).
*/
@Override
protected FileStatus stat(final Path path, final boolean followSymlinks) throws IOException {
java.nio.file.Path nioPath = getNioPath(path);
final BasicFileAttributes attributes;
try {
attributes =
Files.readAttributes(nioPath, BasicFileAttributes.class, linkOpts(followSymlinks));
} catch (java.nio.file.FileSystemException e) {
throw new FileNotFoundException(path + ERR_NO_SUCH_FILE_OR_DIR);
}
FileStatus status = new FileStatus() {
@Override
public boolean isFile() {
return attributes.isRegularFile() || isSpecialFile();
}
@Override
public boolean isSpecialFile() {
return attributes.isOther();
}
@Override
public boolean isDirectory() {
return attributes.isDirectory();
}
@Override
public boolean isSymbolicLink() {
return attributes.isSymbolicLink();
}
@Override
public long getSize() throws IOException {
return attributes.size();
}
@Override
public long getLastModifiedTime() throws IOException {
return attributes.lastModifiedTime().toMillis();
}
@Override
public long getLastChangeTime() {
// This is the best we can do with Java NIO...
return attributes.lastModifiedTime().toMillis();
}
@Override
public long getNodeId() {
// TODO(bazel-team): Consider making use of attributes.fileKey().
return -1;
}
};
return status;
}
/**
* Returns the total size in bytes used by the specified paths. This function guarantees that it
* will not double count overlapping portions of the path set. For example, with a trivial
* overlap of /A and /A, it will count /A only once. It also handles other types of overlaps
* similarly, such as counting /A/B only once given the paths /A and /A/B.
* <p>
* This function is exposed as package private to simplify testing various cases without involving
* an executor. Alternatively this could have been pulled out to a utility class, but it would
* unnecessarily pollute the global namespace.
*/
static long getSpaceUsed(Set<Path> paths) {
ArrayDeque<Path> pathStack = new ArrayDeque<>();
for (Path path : paths) {
pathStack.push(path);
}
// Track the directories we've visited to ensure we're not double counting. It would be
// preferable to resolve overlap once at startup, but the problem is that the filesystem may
// change over time and, in fact, at startup I found that the rocks DB store directory was not
// created by the time the disk space monitor was started.
Set<Path> visited = new HashSet<>();
long totalBytes = 0;
while (!pathStack.isEmpty()) {
try {
// We need to resolve to the real path to ensure that we don't inadvertently double count
// due to different paths to the same directory (e.g. /A and /A/../A).
Path current = pathStack.pop().toRealPath();
if (visited.contains(current)) {
continue;
}
visited.add(current);
BasicFileAttributes currentAttrs = Files.readAttributes(current,
BasicFileAttributes.class);
if (currentAttrs.isDirectory()) {
try (DirectoryStream<Path> directoryListing = Files.newDirectoryStream(current)) {
for (Path child : directoryListing) {
pathStack.push(child);
}
}
} else if (currentAttrs.isRegularFile()) {
totalBytes += currentAttrs.size();
}
} catch (IOException e) {
// If we can't stat the file, just ignore it. This can happen, for example, if we scan
// a directory, but by the time we get to stat'ing the file it has been deleted (e.g.
// due to compaction, rotation, etc.).
}
}
return totalBytes;
}
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);
}
}
}
}