Example usage for java.nio.file Files readAttributes

List of usage examples for java.nio.file Files readAttributes

Introduction

In this page you can find the example usage for java.nio.file Files readAttributes.

Prototype

public static Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options)
        throws IOException 

Source Link

Document

Reads a set of file attributes as a bulk operation.

Usage

From source file:oracle.kv.sample.fileloader.FileLoader.java

/**
 * After successful validation this method is run to load the content of a
 * TXT file into the given table//  www  .  j a v a  2s  . c om
 * 
 * @throws IOException
 */
private void loadData() throws IOException {
    if (inputPathStr != null) {
        dir = new File(inputPathStr);
        File file = null;
        File[] files = null;
        int len = 0;

        // If input path is a directory then load data from all the files
        // that are under the directory. Make sure all the files are of same
        // type
        // i.e. TXT (mix and match is not allowed)
        if (dir.exists()) {
            System.out.println("There are " + dir.listFiles().length + " to be loaded.");
            if (dir.isDirectory()) {
                files = dir.listFiles();
                len = files.length;

                // loop through all the files and load the content one by
                // one
                for (int i = 0; i < len; i++) {
                    file = files[i];
                    try {
                        Path filePath = Paths.get(file.getPath());
                        BasicFileAttributes attr = Files.readAttributes(filePath, BasicFileAttributes.class,
                                LinkOption.NOFOLLOW_LINKS);
                        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
                        FileOwnerAttributeView fileOwnerAttributeView = Files.getFileAttributeView(filePath,
                                FileOwnerAttributeView.class);
                        UserPrincipal userPrincipal = fileOwnerAttributeView.getOwner();

                        id = Integer.toString(i);
                        fileDate = formatter.format(attr.lastAccessTime().toMillis());
                        fileOwner = userPrincipal.getName();
                        binaryFile = FileUtils.readFileToByteArray(file);

                        row = table.createRow();
                        row.put("id", id);
                        row.put("date", fileDate.toString());
                        row.put("owner", fileOwner);
                        row.put("file", binaryFile);

                        tableh.put(row, null, null);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } else {
                System.out.println("There are no Files to Load");
            }
        }
    }

    if (fileId != null) {
        getData();
    }
}

From source file:VOBackupFile.java

/**
 * Wrapper for metadata of backuped file.
 *
 * @param file backuped file/*from   w  w  w .  j ava  2  s.  c  om*/
 */
public VOBackupFile(File file) {
    this.path = file.getAbsolutePath();
    this.directory = file.isDirectory();
    this.symLink = Files.isSymbolicLink(file.toPath());

    this.size = ((file.isDirectory() || symLink) ? 0 : file.length());
    this.modify = new Date(file.lastModified());

    if (symLink) {
        try {
            symlinkTarget = Files.readSymbolicLink(file.toPath()).toString();
        } catch (IOException e) {
            e.printStackTrace(); //TODO Lebeda - oetit do logu
        }
    } else {
        // advanced attributes

        try {

            owner = Files.getOwner(file.toPath(), LinkOption.NOFOLLOW_LINKS).getName();

            if (Files.getFileStore(file.toPath()).supportsFileAttributeView(DosFileAttributeView.class)) {
                dosAttr = Boolean.TRUE;
                final DosFileAttributes dosFileAttributes = Files.readAttributes(file.toPath(),
                        DosFileAttributes.class, LinkOption.NOFOLLOW_LINKS);

                dosArchive = dosFileAttributes.isArchive();
                dosHidden = dosFileAttributes.isHidden();
                dosSystem = dosFileAttributes.isSystem();
                dosReadOnly = dosFileAttributes.isReadOnly();
            } else {
                dosAttr = Boolean.FALSE;
            }

            if (Files.getFileStore(file.toPath()).supportsFileAttributeView(PosixFileAttributeView.class)) {
                posixAttr = Boolean.TRUE;
                final PosixFileAttributes posixFileAttributes = Files.readAttributes(file.toPath(),
                        PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
                posixGroup = posixFileAttributes.group().getName();
                posixPermitions = PosixFilePermissions.toString(posixFileAttributes.permissions());
            } else {
                posixAttr = Boolean.FALSE;
            }

        } catch (IOException e) {
            e.printStackTrace(); //Todo implementovat
        }
    }

}

From source file:com.twosigma.beaker.core.rest.FileIORest.java

@GET
@Path("getPosixFileOwnerAndPermissions")
@Produces(MediaType.APPLICATION_JSON)/* w  ww. j a va 2s  . c  o m*/
public Response getPosixFileOwnerAndPermissions(@QueryParam("path") String pathString) throws IOException {
    pathString = removePrefix(pathString);
    java.nio.file.Path path = Paths.get(pathString);
    if (Files.exists(path)) {
        Map<String, Object> response = new HashMap<>();
        response.put("permissions", Files.getPosixFilePermissions(path));
        response.put("owner", Files.getOwner(path, LinkOption.NOFOLLOW_LINKS).getName());
        response.put("group", Files.readAttributes(path, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
                .group().getName());
        return status(OK).entity(response).build();
    } else {
        return status(BAD_REQUEST).build();
    }
}

From source file:org.panbox.desktop.common.vfs.backend.generic.GenericVirtualFileImpl.java

@Override
public long getCreationTime() {
    try {/*from   ww w .  ja  va2s.  co  m*/
        BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class,
                LinkOption.NOFOLLOW_LINKS);
        return attr.creationTime().toMillis();
    } catch (IOException e) {
        logger.error("Error in getCreationTime()", e);
        return 0;
    }
}

From source file:org.panbox.desktop.common.vfs.backend.generic.GenericVirtualFileImpl.java

@Override
public long getLastAccessTime() {
    try {/*from w w  w.  j  a v a  2  s. c om*/
        BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class,
                LinkOption.NOFOLLOW_LINKS);
        return attr.lastAccessTime().toMillis();
    } catch (IOException e) {
        logger.error("Error in getLastAccessTime()", e);
        return 0;
    }
}

From source file:org.fim.internal.StateGenerator.java

private void scanFileTree(BlockingDeque<Path> filesToHashQueue, Path directory, FimIgnore parentFimIgnore)
        throws NoSuchAlgorithmException {
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
        FimIgnore fimIgnore = fimIgnoreManager.loadLocalIgnore(directory, parentFimIgnore);

        for (Path file : stream) {
            if (!fileHashersStarted && filesToHashQueue.size() > FILES_QUEUE_CAPACITY / 2) {
                startFileHashers();/*www  .j  a  va  2  s. c  om*/
            }

            BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class,
                    LinkOption.NOFOLLOW_LINKS);
            String fileName = file.getFileName().toString();
            if (fimIgnoreManager.isIgnored(fileName, attributes, fimIgnore)) {
                fimIgnoreManager.ignoreThisFiles(file, attributes);
            } else {
                if (attributes.isRegularFile()) {
                    enqueueFile(filesToHashQueue, file);
                } else if (attributes.isDirectory()) {
                    scanFileTree(filesToHashQueue, file, fimIgnore);
                }
            }
        }
    } catch (IOException ex) {
        Console.newLine();
        Logger.error("Skipping - Error scanning directory '" + directory + "'", ex,
                context.isDisplayStackTrace());
    }
}

From source file:org.panbox.desktop.common.vfs.backend.generic.GenericVirtualFileImpl.java

@Override
public long getLastWriteTime() {
    // return file.lastModified();
    try {/*from   w  ww .  j  ava 2  s .  c om*/
        BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class,
                LinkOption.NOFOLLOW_LINKS);
        return attr.lastModifiedTime().toMillis();
    } catch (IOException e) {
        logger.error("Error in getLastWriteTime()", e);
        return 0;
    }
}

From source file:configuration.Util.java

/**
 * Get the owner's group of the current jar file
 * @return the owner's group of the  current jar file
 *///from  www.  ja v  a 2 s . co m
public static String getGroupJar() {
    Path jpath = Paths.get(currentPath());
    try {
        GroupPrincipal group = Files.readAttributes(jpath, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
                .group();
        return group.getName();
    } catch (IOException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Can't get Owner or the jar file");
        System.out.println(ex);
        return "";
    }
}

From source file:org.opendedup.sdfs.filestore.cloud.BatchAwsS3ChunkStore.java

@Override
public void uploadFile(File f, String to, String pp) throws IOException {
    this.s3clientLock.readLock().lock();
    try {/*from   ww w.  j  a v  a 2s .  c  o  m*/
        InputStream in = null;
        while (to.startsWith(File.separator))
            to = to.substring(1);

        String pth = pp + "/" + EncyptUtils.encString(to, Main.chunkStoreEncryptionEnabled);
        SDFSLogger.getLog().info("uploading " + f.getPath() + " to " + to + " pth " + pth);
        boolean isDir = false;
        boolean isSymlink = false;
        if (!OSValidator.isWindows()) {
            isDir = Files.readAttributes(f.toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
                    .isDirectory();
            isSymlink = Files.readAttributes(f.toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
                    .isSymbolicLink();
        } else {
            isDir = f.isDirectory();
        }
        if (isSymlink) {
            try {
                HashMap<String, String> metaData = new HashMap<String, String>();
                metaData.put("encrypt", Boolean.toString(Main.chunkStoreEncryptionEnabled));
                metaData.put("lastmodified", Long.toString(f.lastModified()));
                String slp = EncyptUtils.encString(Files.readSymbolicLink(f.toPath()).toFile().getPath(),
                        Main.chunkStoreEncryptionEnabled);
                metaData.put("symlink", slp);
                ObjectMetadata md = new ObjectMetadata();
                md.setContentType("binary/octet-stream");
                md.setContentLength(pth.getBytes().length);
                md.setUserMetadata(metaData);
                PutObjectRequest req = new PutObjectRequest(this.name, pth,
                        new ByteArrayInputStream(pth.getBytes()), md);
                s3Service.putObject(req);
                if (this.isClustered())
                    this.checkoutFile(pth);
            } catch (Exception e1) {
                throw new IOException(e1);
            }
        } else if (isDir) {
            HashMap<String, String> metaData = FileUtils.getFileMetaData(f, Main.chunkStoreEncryptionEnabled);
            metaData.put("encrypt", Boolean.toString(Main.chunkStoreEncryptionEnabled));
            metaData.put("lastmodified", Long.toString(f.lastModified()));
            metaData.put("directory", "true");
            ObjectMetadata md = new ObjectMetadata();
            md.setContentType("binary/octet-stream");
            md.setContentLength(pth.getBytes().length);
            md.setUserMetadata(metaData);
            try {
                PutObjectRequest req = new PutObjectRequest(this.name, pth,
                        new ByteArrayInputStream(pth.getBytes()), md);
                s3Service.putObject(req);
                if (this.isClustered())
                    this.checkoutFile(pth);
            } catch (Exception e1) {
                SDFSLogger.getLog().error("error uploading", e1);
                throw new IOException(e1);
            }
        } else {
            String rnd = RandomGUID.getGuid();
            File p = new File(this.staged_sync_location, rnd);
            File z = new File(this.staged_sync_location, rnd + ".z");
            File e = new File(this.staged_sync_location, rnd + ".e");
            while (z.exists()) {
                rnd = RandomGUID.getGuid();
                p = new File(this.staged_sync_location, rnd);
                z = new File(this.staged_sync_location, rnd + ".z");
                e = new File(this.staged_sync_location, rnd + ".e");
            }
            try {
                BufferedInputStream is = new BufferedInputStream(new FileInputStream(f));
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(p));
                IOUtils.copy(is, os);
                os.flush();
                os.close();
                is.close();
                if (Main.compress) {
                    CompressionUtils.compressFile(p, z);
                    p.delete();
                    p = z;
                }
                byte[] ivb = null;
                if (Main.chunkStoreEncryptionEnabled) {
                    try {
                        ivb = PassPhrase.getByteIV();
                        EncryptUtils.encryptFile(p, e, new IvParameterSpec(ivb));

                    } catch (Exception e1) {
                        throw new IOException(e1);
                    }
                    p.delete();
                    p = e;
                }
                String objName = pth;
                ObjectMetadata md = new ObjectMetadata();
                Map<String, String> umd = FileUtils.getFileMetaData(f, Main.chunkStoreEncryptionEnabled);
                md.setUserMetadata(umd);
                md.addUserMetadata("lz4compress", Boolean.toString(Main.compress));
                md.addUserMetadata("encrypt", Boolean.toString(Main.chunkStoreEncryptionEnabled));
                if (ivb != null)
                    md.addUserMetadata("ivspec", BaseEncoding.base64().encode(ivb));
                md.addUserMetadata("lastmodified", Long.toString(f.lastModified()));
                if (simpleS3) {
                    md.setContentType("binary/octet-stream");
                    in = new BufferedInputStream(new FileInputStream(p), 32768);
                    try {
                        if (md5sum) {
                            byte[] md5Hash = ServiceUtils.computeMD5Hash(in);
                            in.close();
                            String mds = BaseEncoding.base64().encode(md5Hash);
                            md.setContentMD5(mds);
                            md.addUserMetadata("md5sum", mds);
                        }

                    } catch (NoSuchAlgorithmException e2) {
                        SDFSLogger.getLog().error("while hashing", e2);
                        throw new IOException(e2);
                    }

                    in = new FileInputStream(p);
                    md.setContentLength(p.length());
                    try {
                        PutObjectRequest req = new PutObjectRequest(this.name, objName, in, md);
                        s3Service.putObject(req);
                        if (this.isClustered())
                            this.checkoutFile(pth);
                        SDFSLogger.getLog().debug(
                                "uploaded=" + f.getPath() + " lm=" + md.getUserMetadata().get("lastmodified"));
                    } catch (AmazonS3Exception e1) {
                        if (e1.getStatusCode() == 409) {
                            try {
                                s3Service.deleteObject(this.name, objName);
                                this.uploadFile(f, to, pp);
                                return;
                            } catch (Exception e2) {
                                throw new IOException(e2);
                            }
                        } else {

                            throw new IOException(e1);
                        }
                    } catch (Exception e1) {
                        // SDFSLogger.getLog().error("error uploading", e1);
                        throw new IOException(e1);
                    }
                } else {
                    try {
                        md.setContentType("binary/octet-stream");
                        in = new BufferedInputStream(new FileInputStream(p), 32768);
                        byte[] md5Hash = ServiceUtils.computeMD5Hash(in);
                        in.close();
                        String mds = BaseEncoding.base64().encode(md5Hash);
                        md.setContentMD5(mds);
                        md.addUserMetadata("md5sum", mds);
                        in = new BufferedInputStream(new FileInputStream(p), 32768);

                        md.setContentLength(p.length());
                        PutObjectRequest req = new PutObjectRequest(this.name, objName, in, md);
                        multiPartUpload(req);
                        if (this.isClustered())
                            this.checkoutFile(pth);
                    } catch (AmazonS3Exception e1) {
                        if (e1.getStatusCode() == 409) {
                            try {
                                s3Service.deleteObject(this.name, objName);
                                this.uploadFile(f, to, pp);
                                return;
                            } catch (Exception e2) {
                                throw new IOException(e2);
                            }
                        } else {

                            throw new IOException(e1);
                        }
                    } catch (Exception e1) {
                        // SDFSLogger.getLog().error("error uploading", e1);
                        throw new IOException(e1);
                    }
                }
            } finally {
                try {
                    if (in != null)
                        in.close();
                } finally {
                    p.delete();
                    z.delete();
                    e.delete();
                }
            }
        }
    } finally {
        this.s3clientLock.readLock().unlock();
    }

}