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:org.roda.core.common.monitor.TransferredResourcesScanner.java

public TransferredResource createFile(String parentUUID, String fileName, InputStream inputStream)
        throws GenericException, RequestNotValidException, NotFoundException, AlreadyExistsException {
    Path parentPath;//  w  w w.j  ava 2s.  c o  m
    if (StringUtils.isNotBlank(parentUUID)) {
        TransferredResource parent = index.retrieve(TransferredResource.class, parentUUID, fieldsToReturn);
        parentPath = basePath.resolve(parent.getRelativePath());
    } else {
        parentPath = basePath;
    }

    Path file = parentPath.resolve(fileName);
    try {
        try {
            Files.createDirectories(parentPath);
        } catch (FileAlreadyExistsException e) {
            // do nothing and carry on
        }

        Files.copy(inputStream, file);
        BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
        TransferredResource resource = createTransferredResource(file, attrs, attrs.size(), basePath,
                new Date());
        index.create(TransferredResource.class, resource);
        return resource;
    } catch (FileAlreadyExistsException e) {
        LOGGER.error("Cannot create file", e);
        throw new AlreadyExistsException(file.toString());
    } catch (IOException e) {
        LOGGER.error("Cannot create file", e);
        throw new GenericException("Cannot create file", e);
    }
}

From source file:org.application.backupsync.PathName.java

public JSONObject getAttrs() throws IOException, JSONException {
    JSONObject result;//from  w w w .  ja  v a  2 s. co  m
    BasicFileAttributes attr;
    DosFileAttributes dosAttr;
    PosixFileAttributes posixAttr;

    result = new JSONObject();
    attr = Files.readAttributes(this.path, BasicFileAttributes.class);

    result.append("ctime", attr.creationTime().toMillis());
    result.append("mtime", attr.lastModifiedTime().toMillis());
    //result.append("symlink", attr.isSymbolicLink()); //Redundant
    result.append("size", attr.size());

    if (System.getProperty("os.name").startsWith("Windows")) {
        dosAttr = Files.readAttributes(this.path, DosFileAttributes.class);

        result.append("dos:archive", dosAttr.isArchive());
        result.append("dos:hidden", dosAttr.isHidden());
        result.append("dos:readonly", dosAttr.isReadOnly());
        result.append("dos:system", dosAttr.isSystem());
    } else {
        posixAttr = Files.readAttributes(this.path, PosixFileAttributes.class);

        result.append("posix:symlink", posixAttr.isSymbolicLink());
        result.append("posix:owner", posixAttr.owner());
        result.append("posix:group", posixAttr.group());
        result.append("posix:permission", PosixFilePermissions.toString(posixAttr.permissions()));
    }

    return result;
}

From source file:org.mangelp.fakeSmtpWeb.httpServer.mailBrowser.MailFile.java

protected void getAttributes() throws IOException {
    BasicFileAttributes attr = Files.readAttributes(this.getFile().toPath(), BasicFileAttributes.class);

    this.setCreationDate(new Date(attr.creationTime().toMillis()));
    this.setSize(attr.size());
}

From source file:ubicrypt.core.provider.LocalRepository.java

@Override
public Observable<Boolean> save(final FileProvenience fp) {
    try {/*from  w  w w.j  a va 2  s . co m*/
        check(fp);
        final UbiFile rfile = fp.getFile();
        final Optional<LocalFile> lfile = localConfig.getLocalFiles().stream().filter(lf -> lf.equals(rfile))
                .findFirst();
        //if path not set, take the getName()
        final Path path = rfile.getPath() != null ? rfile.getPath() : Paths.get(rfile.getName());
        if (!lfile.isPresent()) {
            if (!rfile.isDeleted() && !rfile.isRemoved()) {
                log.info("copy to:{} from repo:{}, file:{} ", basePath.resolve(path), fp.getOrigin(),
                        rfile.getPath());
                final LocalFile lc = new LocalFile();
                lc.copyFrom(rfile);
                localConfig.getLocalFiles().add(lc);
                if (Files.exists(basePath.resolve(path))) {
                    final BasicFileAttributes attrs = SupplierExp.silent(
                            () -> Files.readAttributes(basePath.resolve(path), BasicFileAttributes.class));
                    if (attrs.isDirectory()) {
                        log.info("can't import file, a folder already exists with the same name:{}", path);
                        return Observable.just(false);
                    }
                    if (attrs.size() == rfile.getSize()) {
                        log.info("identical file already present locally:{}", path);
                        localConfig.getLocalFiles().add(LocalFile.copy(rfile));
                        return Observable.just(true).doOnCompleted(() -> fileEvents.onNext(
                                new FileEvent(rfile, FileEvent.Type.created, FileEvent.Location.local)));
                    }
                    log.info("conflicting file already present locally:{}", path);
                    conflictEvents.onNext(rfile);
                    return Observable.just(false);
                }
                AtomicReference<Path> tempFile = new AtomicReference<>();
                return fp.getOrigin().get(rfile).flatMap(new StoreTempFile()).doOnNext(tempFile::set)
                        .map(new CopyFile(rfile.getSize(), basePath.resolve(path), true,
                                fp.getFile().getLastModified()))
                        .doOnCompleted(() -> {
                            if (tempFile.get() != null) {
                                try {
                                    Files.delete(tempFile.get());
                                } catch (IOException e) {
                                }
                            }
                        }).doOnCompleted(() -> localConfig.getLocalFiles().add(LocalFile.copy(rfile)))
                        .doOnCompleted(() -> fileEvents.onNext(
                                new FileEvent(rfile, FileEvent.Type.created, FileEvent.Location.local)));
            }
            //if present
        } else {
            if (rfile.getVclock().compare(lfile.get().getVclock()) == VClock.Comparison.newer) {
                lfile.get().copyFrom(rfile);
                if (!rfile.isDeleted() && !rfile.isRemoved()) {
                    log.info("update file:{} locally from repo:{}", rfile.getPath(), fp.getOrigin());
                    AtomicReference<Path> tempFile = new AtomicReference<>();
                    return fp.getOrigin().get(fp.getFile()).flatMap(new StoreTempFile())
                            .map(new CopyFile(rfile.getSize(), basePath.resolve(path), false,
                                    fp.getFile().getLastModified()))
                            .doOnCompleted(() -> {
                                if (tempFile.get() != null) {
                                    try {
                                        Files.delete(tempFile.get());
                                    } catch (IOException e) {
                                    }
                                }
                            }).doOnCompleted(() -> fileEvents.onNext(new FileEvent(fp.getFile(),
                                    FileEvent.Type.updated, FileEvent.Location.local)));
                }
                //removed or deleted
                fileEvents.onNext(new FileEvent(fp.getFile(),
                        rfile.isDeleted() ? FileEvent.Type.deleted : FileEvent.Type.removed,
                        FileEvent.Location.local));

            }
        }
        return Observable.just(false);
    } catch (Exception e) {
        return Observable.error(e);
    }
}

From source file:com.arpnetworking.tsdcore.tailer.StatefulTailer.java

private Attributes getAttributes(final File file, final Optional<Long> lastChecked) throws IOException {
    final BasicFileAttributes attributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
    LOGGER.trace(String.format("File attributes; file=%s, lastModifiedTime=%d, size=%d", file,
            Long.valueOf(attributes.lastModifiedTime().toMillis()), Long.valueOf(attributes.size())));

    return new Attributes(attributes.size(), attributes.lastModifiedTime().toMillis(), lastChecked.isPresent()
            && attributes.lastModifiedTime().toMillis() > lastChecked.get().longValue());
}

From source file:com.arpnetworking.metrics.common.tailer.StatefulTailer.java

private Attributes getAttributes(final Path file, final Optional<Long> lastChecked) throws IOException {
    final BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);
    LOGGER.trace().setMessage("File attributes").addData("file", file)
            .addData("lastModifiedTime", attributes.lastModifiedTime().toMillis())
            .addData("size", attributes.size()).log();

    return new Attributes(attributes.size(), attributes.lastModifiedTime().toMillis(),
            lastChecked.isPresent() && attributes.lastModifiedTime().toMillis() > lastChecked.get());
}

From source file:io.uploader.drive.drive.largefile.GDriveUpload.java

protected String uploadFile(boolean update) throws IOException {

    Preconditions.checkState(update == (fileId != null));

    DriveResumableUpload upload = null;/*from  ww  w  .  j  av a2s  .c o m*/
    BasicFileAttributes attr = null;
    File fstatus = null;
    try {
        String googleLocation;
        String filestatus = tmpFilePath;
        attr = io.uploader.drive.util.FileUtils.getFileAttr(Paths.get(filename));

        fstatus = new File(filestatus);
        if (fstatus.exists()) {
            BufferedReader in = new BufferedReader(new FileReader(filestatus));
            md5 = in.readLine();
            googleLocation = in.readLine();
            in.close();

            if (update) {
                upload = new DriveResumableUpload(config.getHttpProxySettings(), new DriveAuth(config),
                        googleLocation, fileId, mimeType, filename, attr.size(), progressCallback);
            } else {
                upload = new DriveResumableUpload(config.getHttpProxySettings(), new DriveAuth(config),
                        googleLocation, title, description, parentId, mimeType, filename, attr.size(),
                        progressCallback);
            }
        } else {
            if (md5 == null) {
                FileInputStream fis = new FileInputStream(new File(filename));
                md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
                logger.info("md5: " + md5);
                fis.close();
            }
            // Completely new upload. location: null
            if (update) {
                upload = new DriveResumableUpload(config.getHttpProxySettings(), new DriveAuth(config), null,
                        fileId, mimeType, filename, attr.size(), progressCallback);
            } else {
                upload = new DriveResumableUpload(config.getHttpProxySettings(), new DriveAuth(config), null,
                        title, description, parentId, mimeType, filename, attr.size(), progressCallback);
            }

            // Write location and md5 to file for later resume
            BufferedWriter out = new BufferedWriter(new FileWriter(filestatus));
            out.write(md5 + "\n" + upload.getLocation() + "\n");
            out.close();
        }
    } catch (URISyntaxException e) {
        logger.error("Error occurred while uploading files", e);
        throw new RuntimeException("Error occurred while uploading files " + e.getMessage());
    }
    try {
        String ret = uploadFile(upload, attr);
        if (fstatus != null && fstatus.exists()) {
            fstatus.delete();
        }
        return ret;
    } catch (TransferException e) {
        if (e.isNotResumable()) {
            if (fstatus != null && fstatus.exists()) {
                fstatus.delete();
            }
        }
        throw new IOException(e.getMessage());
    }
}

From source file:de.tiqsolutions.hdfs.BasicFileAttributeViewImpl.java

Map<String, Object> readAttributes(String attributes) throws IOException {
    BasicFileAttributes attr = readAttributes();
    List<String> attrlist = Arrays.asList(attributes.split(","));
    boolean readall = attrlist.contains("*");
    Map<String, Object> ret = new HashMap<>();
    if (readall || attrlist.contains("fileKey"))
        ret.put("fileKey", attr.fileKey());
    if (readall || attrlist.contains("creationTime"))
        ret.put("creationTime", attr.creationTime());
    if (readall || attrlist.contains("isDirectory"))
        ret.put("isDirectory", attr.isDirectory());
    if (readall || attrlist.contains("isOther"))
        ret.put("isOther", attr.isOther());
    if (readall || attrlist.contains("isRegularFile"))
        ret.put("isRegularFile", attr.isRegularFile());
    if (readall || attrlist.contains("isSymbolicLink"))
        ret.put("isSymbolicLink", attr.isSymbolicLink());
    if (readall || attrlist.contains("lastAccessTime"))
        ret.put("lastAccessTime", attr.lastAccessTime());
    if (readall || attrlist.contains("lastModifiedTime"))
        ret.put("lastModifiedTime", attr.lastModifiedTime());
    if (readall || attrlist.contains("size"))
        ret.put("size", attr.size());
    return ret;//  ww w  .j a va  2 s. c  o  m
}

From source file:io.fabric8.docker.client.impl.BuildImage.java

@Override
public OutputHandle fromFolder(String path) {
    try {/*  w w w .  jav a2s  . com*/
        final Path root = Paths.get(path);
        final Path dockerIgnore = root.resolve(DOCKER_IGNORE);
        final List<String> ignorePatterns = new ArrayList<>();
        if (dockerIgnore.toFile().exists()) {
            for (String p : Files.readAllLines(dockerIgnore, UTF_8)) {
                ignorePatterns.add(path.endsWith(File.separator) ? path + p : path + File.separator + p);
            }
        }

        final DockerIgnorePathMatcher dockerIgnorePathMatcher = new DockerIgnorePathMatcher(ignorePatterns);

        File tempFile = Files.createTempFile(Paths.get(DEFAULT_TEMP_DIR), DOCKER_PREFIX, BZIP2_SUFFIX).toFile();

        try (FileOutputStream fout = new FileOutputStream(tempFile);
                BufferedOutputStream bout = new BufferedOutputStream(fout);
                BZip2CompressorOutputStream bzout = new BZip2CompressorOutputStream(bout);
                final TarArchiveOutputStream tout = new TarArchiveOutputStream(bzout)) {
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (dockerIgnorePathMatcher.matches(dir)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (dockerIgnorePathMatcher.matches(file)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    final Path relativePath = root.relativize(file);
                    final TarArchiveEntry entry = new TarArchiveEntry(file.toFile());
                    entry.setName(relativePath.toString());
                    entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE);
                    entry.setSize(attrs.size());
                    tout.putArchiveEntry(entry);
                    Files.copy(file, tout);
                    tout.closeArchiveEntry();
                    return FileVisitResult.CONTINUE;
                }
            });
            fout.flush();
        }
        return fromTar(tempFile.getAbsolutePath());

    } catch (IOException e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:org.fim.internal.hash.FileHasher.java

@Override
public void run() {
    try {//from  www.  j a va  2s  .c  om
        Path file;
        while ((file = filesToHashQueue.poll(500, TimeUnit.MILLISECONDS)) != null) {
            try {
                BasicFileAttributes attributes;
                List<Attribute> fileAttributes = null;

                if (SystemUtils.IS_OS_WINDOWS) {
                    DosFileAttributes dosFileAttributes = Files.readAttributes(file, DosFileAttributes.class);
                    fileAttributes = addAttribute(fileAttributes, FileAttribute.DosFilePermissions,
                            DosFilePermissions.toString(dosFileAttributes));
                    attributes = dosFileAttributes;
                } else {
                    PosixFileAttributes posixFileAttributes = Files.readAttributes(file,
                            PosixFileAttributes.class);
                    fileAttributes = addAttribute(fileAttributes, FileAttribute.PosixFilePermissions,
                            PosixFilePermissions.toString(posixFileAttributes.permissions()));
                    if (SELinux.ENABLED) {
                        fileAttributes = addAttribute(fileAttributes, FileAttribute.SELinuxLabel,
                                SELinux.getLabel(context, file));
                    }
                    attributes = posixFileAttributes;
                }

                hashProgress.updateOutput(attributes.size());

                FileHash fileHash = hashFile(file, attributes.size());
                String normalizedFileName = FileUtil.getNormalizedFileName(file);
                String relativeFileName = FileUtil.getRelativeFileName(rootDir, normalizedFileName);

                fileStates.add(new FileState(relativeFileName, attributes, fileHash, fileAttributes));
            } catch (Exception ex) {
                Console.newLine();
                Logger.error("Skipping - Error hashing file '" + file + "'", ex, context.isDisplayStackTrace());
            }
        }
    } catch (InterruptedException ex) {
        Logger.error("Exception while hashing", ex, context.isDisplayStackTrace());
    }
}