Example usage for java.nio.file.attribute BasicFileAttributes size

List of usage examples for java.nio.file.attribute BasicFileAttributes size

Introduction

In this page you can find the example usage for java.nio.file.attribute BasicFileAttributes size.

Prototype

long size();

Source Link

Document

Returns the size of the file (in bytes).

Usage

From source file:Main.java

public static void main(String[] args) {
    Path path = Paths.get("C:\\Java_Dev\\test1.txt");

    try {/*from w ww.  ja va  2  s  .c om*/
        BasicFileAttributeView bfv = Files.getFileAttributeView(path, BasicFileAttributeView.class);
        BasicFileAttributes bfa = bfv.readAttributes();

        System.out.format("Size:%s bytes %n", bfa.size());
        System.out.format("Creation  Time:%s %n", bfa.creationTime());
        System.out.format("Last Access  Time:%s %n", bfa.lastAccessTime());

        FileTime newLastModifiedTime = null;
        FileTime newLastAccessTime = null;
        FileTime newCreateTime = FileTime.from(Instant.now());

        bfv.setTimes(newLastModifiedTime, newLastAccessTime, newCreateTime);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) {
    Path path = Paths.get("C:\\Java_Dev\\test1.txt");

    try {/*from w  w w.j  a  va 2s  . co  m*/
        BasicFileAttributes bfa = Files.readAttributes(path, BasicFileAttributes.class);
        System.out.format("Size:%s bytes %n", bfa.size());
        System.out.format("Creation Time:%s %n", bfa.creationTime());
        System.out.format("Last Access  Time:%s %n", bfa.lastAccessTime());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {

    BasicFileAttributes attr = null;
    Path path = Paths.get("C:/tutorial/Java/JavaFX", "Topic.txt");

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

    System.out.println("File size: " + attr.size());

}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path path = FileSystems.getDefault().getPath("/home/docs/users.txt");
    // BasicFileAttributes attributes = Files.readAttributes(path,
    // BasicFileAttributes.class);
    BasicFileAttributeView view = Files.getFileAttributeView(path, BasicFileAttributeView.class);
    BasicFileAttributes attributes = view.readAttributes();

    System.out.println("Creation Time: " + attributes.creationTime());
    System.out.println("Last Accessed Time: " + attributes.lastAccessTime());
    System.out.println("Last Modified Time: " + attributes.lastModifiedTime());
    System.out.println("File Key: " + attributes.fileKey());
    System.out.println("Directory: " + attributes.isDirectory());
    System.out.println("Other Type of File: " + attributes.isOther());
    System.out.println("Regular File: " + attributes.isRegularFile());
    System.out.println("Symbolic File: " + attributes.isSymbolicLink());
    System.out.println("Size: " + attributes.size());
}

From source file:Main.java

public static FileVisitor<Path> getFileVisitor() {
    class DirVisitor<Path> extends SimpleFileVisitor<Path> {
        @Override//ww  w . j a  va  2  s.c  om
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {

            System.out.format("%s [Directory]%n", dir);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            System.out.format("%s [File,  Size: %s  bytes]%n", file, attrs.size());
            return FileVisitResult.CONTINUE;
        }
    }
    FileVisitor<Path> visitor = new DirVisitor<>();
    return visitor;
}

From source file:org.dishevelled.thumbnail.examples.ThumbnailDrop.java

/**
 * Return true if the specified path is a non-empty regular file.
 *
 * @param path path/*  w ww .ja va2 s.c o m*/
 * @return true if the specified path is a non-empty regular file
 * @throws IOException if an I/O error occurs
 */
static boolean isNonEmpty(final Path path) throws IOException {
    BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
    return attr.isRegularFile() && (attr.size() > 0L);
}

From source file:org.roda.core.common.RodaUtils.java

/**
 * @deprecated 20160907 hsilva: not seeing any method using it, so it will be
 *             removed soon//from  w w w .java  2 s.c  o m
 */
@Deprecated
public static long getPathSize(Path startPath) throws IOException {
    final AtomicLong size = new AtomicLong(0);

    Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            size.addAndGet(attrs.size());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            // Skip folders that can't be traversed
            return FileVisitResult.CONTINUE;
        }
    });

    return size.get();
}

From source file:io.uploader.drive.drive.DriveUtils.java

/**
 * Update an existing file's metadata and content.
 * //from w ww .ja  v a2 s  .co  m
 * @param config
 *            Configuration object.
 * @param service
 *            Drive API service instance.
 * @param fileId
 *            ID of the file to update.
 * @param newTitle
 *            New title for the file.
 * @param newDescription
 *            New description for the file.
 * @param newMimeType
 *            New MIME type for the file.
 * @return Updated file metadata if successful, {@code null} otherwise.
 * @throws IOException
 */
public static File updateFile(HasConfiguration config, Drive service, HasId fileId, String newTitle,
        HasDescription newDescription, HasMimeType newMimeType, String filename,
        InputStreamProgressFilter.StreamProgressCallback progressCallback) throws IOException {

    Preconditions.checkNotNull(fileId);
    if (org.apache.commons.lang3.StringUtils.isEmpty(fileId.getId())) {
        throw new IllegalArgumentException();
    }

    // First retrieve the file from the API.
    File file = service.files().get(fileId.getId()).execute();

    // File's new metadata.
    if (org.apache.commons.lang3.StringUtils.isNotEmpty(newTitle)) {
        file.setTitle(newTitle);
    }
    if (newDescription != null) {
        file.setDescription(newDescription.getDescription());
    }
    if (newMimeType != null) {
        file.setMimeType(newMimeType.getMimeType());
    }

    // if large file, the same bug as for uploading exists, therefore we currently need to rely on the old api
    // see: https://code.google.com/p/google-api-python-client/issues/detail?id=231
    boolean useOldApi = true;
    boolean useMediaUpload = false;

    DriveFileContent mediaContent = null;
    if (org.apache.commons.lang3.StringUtils.isNotEmpty(filename)) {

        BasicFileAttributes attr = io.uploader.drive.util.FileUtils.getFileAttr(Paths.get(filename));
        useMediaUpload = (attr != null && attr.size() > largeFileMinimumSize);

        java.io.File fileContent = new java.io.File(filename);
        mediaContent = new DriveFileContent(file.getMimeType(), fileContent, progressCallback);
    }

    // Send the request to the API.
    File updatedFile = null;
    if (useMediaUpload) {
        // update metadata
        logger.info("Update metadata");
        updatedFile = service.files().update(fileId.getId(), file).execute();

        // we need to upload the new media content
        logger.info("Update content");
        if (useOldApi) {
            GDriveUpdater upload = new GDriveUpdater(config, newId(updatedFile.getId()), newMimeType, filename,
                    progressCallback);
            upload.updateFile();
        } else {
            // TODO:
            // ...
            throw new IllegalStateException("Not implemented");
        }
        updatedFile = getFile(service, newId(updatedFile.getId()));
    } else {
        // update metadata, and content (if any) of small files
        if (mediaContent != null) {
            updatedFile = service.files().update(fileId.getId(), file, mediaContent).execute();
        } else {
            updatedFile = service.files().update(fileId.getId(), file).execute();
        }
    }
    return updatedFile;
}

From source file:io.uploader.drive.drive.DriveUtils.java

/**
 * Insert new file.//from ww  w  . j av  a2s  .  co  m
 * 
 * @param config
 *            Configuration object.
 * @param service
 *            Drive API service instance.
 * @param title
 *            Title of the file to insert, including the extension.
 * @param description
 *            Description of the file to insert.
 * @param parentId
 *            Optional parent folder's ID.
 * @param mimeType
 *            MIME type of the file to insert.
 * @param filename
 *            Filename of the file to insert.
 * @return Inserted file metadata if successful, {@code null} otherwise.
 * @throws IOException
 */
public static File insertFile(HasConfiguration config, Drive service, String title, HasDescription description,
        HasId parentId, HasMimeType mimeType, String filename,
        InputStreamProgressFilter.StreamProgressCallback progressCallback) throws IOException {

    if (service == null || org.apache.commons.lang3.StringUtils.isEmpty(title)
            || org.apache.commons.lang3.StringUtils.isEmpty(filename)) {
        throw new IllegalArgumentException();
    }

    final String type = (mimeType == null) ? (null) : (mimeType.getMimeType());

    // File's metadata.
    File body = new File();
    body.setTitle(title);
    body.setDescription((description == null) ? (null) : (description.getDescription()));
    body.setMimeType(type);
    body.setOriginalFilename(filename);

    // Set the parent folder.
    if (parentId != null) {
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(parentId.getId())) {
            body.setParents(Arrays.asList(new ParentReference().setId(parentId.getId())));
        }
    }

    // https://code.google.com/p/google-api-java-client/wiki/MediaUpload
    BasicFileAttributes attr = io.uploader.drive.util.FileUtils.getFileAttr(Paths.get(filename));
    boolean useMediaUpload = (attr != null && attr.size() > largeFileMinimumSize);

    boolean useOldApi = true;
    boolean useCustomMediaUpload = true;

    if (useMediaUpload) {
        File file = null;

        // if large file, there exists a nasty bug in the new API which remains unresolved, 
        // therefore we currently need to rely on the old API (even though it has been deprecated...)
        // see: https://code.google.com/p/google-api-python-client/issues/detail?id=231
        if (useOldApi) {
            GDriveUploader upload = new GDriveUploader(config, title, description, parentId, mimeType, filename,
                    progressCallback);

            String fileId = upload.uploadFile();
            Preconditions.checkState(org.apache.commons.lang3.StringUtils.isNotEmpty(fileId));
            // get the file from response
            file = getFile(service, newId(fileId));
        } else {
            logger.info("Media Upload is used for large files");
            java.io.File mediaFile = new java.io.File(filename);
            InputStreamContent mediaContent = new InputStreamContent(type,
                    new BufferedInputStream(io.uploader.drive.util.FileUtils.getInputStreamWithProgressFilter(
                            progressCallback, mediaFile.length(), new FileInputStream(mediaFile))));

            mediaContent.setRetrySupported(true);
            // TODO: there seems to exist a bug when the size is set... (java.io.IOException: insufficient data written)
            // ...
            //mediaContent.setLength(mediaFile.length());
            mediaContent.setLength(-1);

            Drive.Files.Insert request = service.files().insert(body, mediaContent);

            if (useCustomMediaUpload) {
                MediaHttpUploader mediaHttpUploader = new MediaHttpUploader(mediaContent,
                        request.getAbstractGoogleClient().getRequestFactory().getTransport(),
                        request.getAbstractGoogleClient().getRequestFactory().getInitializer());

                mediaHttpUploader.setDisableGZipContent(true);
                mediaHttpUploader.setProgressListener(new CustomProgressListener());

                HttpResponse response = mediaHttpUploader.upload(request.buildHttpRequestUrl());
                try {
                    if (!response.isSuccessStatusCode()) {
                        logger.error("Error occurred while transferring the large file: "
                                + response.getStatusMessage() + " (Status code: " + response.getStatusCode()
                                + ")");
                    }
                    file = response.parseAs(com.google.api.services.drive.model.File.class);
                } finally {
                    response.disconnect();
                }

            } else {
                request.getMediaHttpUploader().setDisableGZipContent(true);
                request.getMediaHttpUploader().setProgressListener(new CustomDriveApiProgressListener());
                request.setDisableGZipContent(true);
                file = request.execute();
            }
        }
        return file;
    } else {
        // File's content.
        java.io.File fileContent = new java.io.File(filename);
        DriveFileContent mediaContent = new DriveFileContent(type, fileContent, progressCallback);
        Insert insert = service.files().insert(body, mediaContent);
        return insert.execute();
    }
}

From source file:jduagui.Controller.java

public static void getExtensions(String startPath, Map<String, Extension> exts) throws IOException {
    final AtomicReference<String> extension = new AtomicReference<>("");
    final File f = new File(startPath);
    final String str = "";
    Path path = Paths.get(startPath);

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override/*from www.  j av  a  2  s. c  om*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            storageCache.put(file.toAbsolutePath().toString(), attrs.size());
            extension.set(FilenameUtils.getExtension(file.toAbsolutePath().toString()));

            if (extension.get().equals(str)) {
                if (exts.containsKey(noExt)) {
                    exts.get(noExt).countIncrement();
                    exts.get(noExt).increaseSize(attrs.size());
                } else {
                    exts.put(noExt, new Extension(new AtomicLong(1), new AtomicLong(attrs.size())));
                }
            } else {

                if (exts.containsKey(extension.get())) {
                    exts.get(extension.get()).countIncrement();
                    exts.get(extension.get()).increaseSize(attrs.size());
                } else {
                    exts.put(extension.get(), new Extension(new AtomicLong(1), new AtomicLong(attrs.size())));
                }
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }
    });
}