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

The following examples show how to use java.nio.file.attribute.BasicFileAttributes#size() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: JavaRushTasks   File: SearchFileVisitor.java    License: MIT License 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 2
Source Project: buck   File: DirectoryCleaner.java    License: Apache License 2.0 6 votes vote down vote up
private PathStats computePathStats(Path path) throws IOException {
  // Note this will change the lastAccessTime of the file.
  BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);

  if (attributes.isDirectory()) {
    return new PathStats(
        path,
        computeDirSizeBytesRecursively(path),
        attributes.creationTime().toMillis(),
        attributes.lastAccessTime().toMillis());
  } else if (attributes.isRegularFile()) {
    return new PathStats(
        path,
        attributes.size(),
        attributes.creationTime().toMillis(),
        attributes.lastAccessTime().toMillis());
  }

  throw new IllegalArgumentException(
      String.format("Argument path [%s] is not a valid file or directory.", path.toString()));
}
 
Example 3
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    String name = IOHelper.toString(inputAssetDir.relativize(file));
    LogHelper.subInfo("Indexing: '%s'", name);

    // Add to index and copy file
    String digest = SecurityHelper.toHex(SecurityHelper.digest(DigestAlgorithm.SHA1, file));
    IndexObject obj = new IndexObject(attrs.size(), digest);
    objects.add(name, gson.toJsonTree(obj));
    IOHelper.copy(file, resolveObjectFile(outputAssetDir, digest));

    // Continue visiting
    return super.visitFile(file, attrs);
}
 
Example 4
public final void setContentFile(final Path contentFile)
{
    this.contentFile = contentFile;
    
    if (contentFile != null)
    {
        // stat the file, to find out a few key details
        contentFileExists = Files.exists(contentFile, LinkOption.NOFOLLOW_LINKS);
        
        if (contentFileExists)
        {
            try
            {
                BasicFileAttributes attrs = Files.readAttributes(contentFile, BasicFileAttributes.class);

                contentFileIsReadable = Files.isReadable(contentFile);
                contentFileSize       = attrs.size();
                contentFileModified   = new Date(attrs.lastModifiedTime().toMillis());
                contentFileCreated    = new Date(attrs.creationTime().toMillis());

                if (Files.isRegularFile(contentFile, LinkOption.NOFOLLOW_LINKS))
                {
                    contentFileType = FileType.FILE;
                }
                else if (Files.isDirectory(contentFile, LinkOption.NOFOLLOW_LINKS))
                {
                    contentFileType = FileType.DIRECTORY;
                }
                else
                {
                    contentFileType = FileType.OTHER;
                }
            }
            catch (IOException e)
            {
                logger.error("Attributes for file '" + FileUtils.getFileName(contentFile) + "' could not be read.", e);
            }
        }
    }
}
 
Example 5
Source Project: Elasticsearch   File: FileWatcher.java    License: Apache License 2.0 5 votes vote down vote up
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 6
/**
 * Construct a {@link File} with a version and readContent
 *
 * @param name
 * @param extension
 * @param path
 * @return
 * @throws IOException
 */
private File constructFile(String name, String extension, Path path) throws IOException {

    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
    long size = attrs.size();

    String content = null;
    if ((!readableExtensionSet.contains(extension) && !"".equals(extension))
        || size > Constants.MAX_SIZE_FOR_INDEXING_ONE_FILE) {
        log.trace("parsing only name on file : {}", path);
    } else {
        content = readContent(path);
    }

    File fichier = new File(
        UUID.randomUUID().toString(),
        name,
        extension,
        path.toString(),
        null,
        content,
        null,
        size
    );
    setVersionAndProject(fichier, path.toString());
    fichier.setCreatedDate(attrs.creationTime().toInstant().atZone(ZoneId.systemDefault()));
    fichier.setLastModifiedDate(attrs.lastModifiedTime().toInstant().atZone(ZoneId.systemDefault()));

    return fichier;
}
 
Example 7
private boolean isUnzipRequired(ZipEntry entry, Path target) {
    try {
        BasicFileAttributes fileAttributes = Files.readAttributes(target, BasicFileAttributes.class);
        //entry does not contain size when read by ZipInputStream, assume equal size and just compare last modified
        return !entry.isDirectory()
            && !(fileTimeEquals(entry.getLastModifiedTime(), fileAttributes.lastModifiedTime())
                && (entry.getSize() == -1 || entry.getSize() == fileAttributes.size()));
    } catch (IOException e) {
        LOGGER.warn("Target path {} does not exist.", target);
        return true;
    }
}
 
Example 8
protected boolean hasBeenModified(BasicFileAttributes originalAttributes, BasicFileAttributes newAttributes) {
	if(newAttributes.lastModifiedTime().toMillis() > System.currentTimeMillis()) {
		handleWarning_ModifiedTimeInTheFuture(newAttributes.lastModifiedTime());
	}
	
	return 
			originalAttributes == null ||
			originalAttributes.lastModifiedTime().toMillis() != newAttributes.lastModifiedTime().toMillis() ||
			originalAttributes.size() != newAttributes.size();
}
 
Example 9
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;
}
 
Example 10
@Override
public RsyncFileAttributes stat(Path path) throws IOException
{
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class,
                                                     LinkOption.NOFOLLOW_LINKS);
    return new RsyncFileAttributes(toMode(attrs),
                                   attrs.size(),
                                   attrs.lastModifiedTime().to(TimeUnit.SECONDS),
                                   _defaultUser, _defaultGroup);
}
 
Example 11
Source Project: es6draft   File: Resources.java    License: MIT License 5 votes vote down vote up
@Override
public FileVisitResult visitFile(PATH path, BasicFileAttributes attrs) throws IOException {
    Path file = basedir.relativize(path);
    if (attrs.isRegularFile() && attrs.size() != 0L && fileMatcher.matches(file)) {
        return FileVisitResult.CONTINUE;
    }
    return FileVisitResult.TERMINATE;
}
 
Example 12
Source Project: JavaRushTasks   File: Solution.java    License: MIT License 4 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    totalFiles += 1;
    totalSize = totalSize + attrs.size();
    return CONTINUE;
}
 
Example 13
Source Project: Elasticsearch   File: FileWatcher.java    License: Apache License 2.0 4 votes vote down vote up
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 14
/**
 * 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;
}
 
Example 15
/** {@inheritDoc} */
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    size += attrs.size();
    return FileVisitResult.CONTINUE;
}
 
Example 16
Source Project: bazel   File: JavaIoFileSystem.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 17
Source Project: es6draft   File: ScriptCache.java    License: MIT License 4 votes vote down vote up
private CacheKey keyFor(Path path) throws IOException {
    BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
    return new CacheKey(path.toUri().normalize(), attributes.size(), attributes.lastModifiedTime().toMillis());
}
 
Example 18
Source Project: genie   File: DirectoryManifest.java    License: Apache License 2.0 4 votes vote down vote up
private ManifestEntry buildEntry(
    final Path entry,
    final BasicFileAttributes attributes,
    final boolean directory
) throws IOException {
    final String path = this.root.relativize(entry).toString();
    final Path fileName = entry.getFileName();
    final String name = fileName == null
        ? EMPTY_STRING
        : fileName.toString();
    final Instant lastModifiedTime = attributes.lastModifiedTime().toInstant();
    final Instant lastAccessTime = attributes.lastAccessTime().toInstant();
    final Instant creationTime = attributes.creationTime().toInstant();
    final long size = attributes.size();

    String md5 = null;
    String mimeType = null;
    if (!directory) {
        if (this.checksumFiles) {
            try (InputStream data = Files.newInputStream(entry, StandardOpenOption.READ)) {
                md5 = DigestUtils.md5Hex(data);
            } catch (final IOException ioe) {
                // For now MD5 isn't critical or required so we'll swallow errors here
                log.error("Unable to create MD5 for {} due to error", entry, ioe);
            }
        }

        mimeType = this.getMimeType(name, entry);
    }

    final Set<String> children = Sets.newHashSet();
    if (directory) {
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(entry)) {
            for (final Path child : directoryStream) {
                children.add(this.root.relativize(child).toString());
            }
        }
    }

    String parent = null;
    if (StringUtils.isNotEmpty(path)) {
        // Not the root
        parent = this.root.relativize(entry.getParent()).toString();
    }

    return new ManifestEntry(
        path,
        name,
        lastModifiedTime,
        lastAccessTime,
        creationTime,
        directory,
        size,
        md5,
        mimeType,
        parent,
        children
    );
}
 
Example 19
@Test
public void file_size_nio () throws IOException {

	BasicFileAttributes attr = Files.readAttributes(source, BasicFileAttributes.class);

	long fileSize = attr.size();
	
	assertEquals(29, fileSize);
}
 
Example 20
Source Project: mycore   File: MCRNode.java    License: GNU General Public License v3.0 2 votes vote down vote up
/**
 * For file nodes, returns the file content size in bytes, otherwise returns
 * 0.
 * 
 * @return the file size in bytes
 */
public long getSize() throws IOException {
    BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
    return attr.isRegularFile() ? attr.size() : 0;
}