Java Code Examples for java.nio.file.Files#readAttributes()
The following examples show how to use
java.nio.file.Files#readAttributes() .
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 check out the related API usage on the sidebar.
Example 1
Source File: LocalAttributesFinderFeatureTest.java From cyberduck with GNU General Public License v3.0 | 8 votes |
@Test public void testConvert() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); if(session.isPosixFilesystem()) { session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback()); final Path file = new Path(new LocalHomeFinderFeature(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new LocalTouchFeature(session).touch(file, new TransferStatus()); final java.nio.file.Path local = session.toPath(file); final PosixFileAttributes posixAttributes = Files.readAttributes(local, PosixFileAttributes.class); final LocalAttributesFinderFeature finder = new LocalAttributesFinderFeature(session); assertEquals(PosixFilePermissions.toString(posixAttributes.permissions()), finder.find(file).getPermission().getSymbol()); Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-------")); assertEquals("rw-------", finder.find(file).getPermission().getSymbol()); Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rwxrwxrwx")); assertEquals("rwxrwxrwx", finder.find(file).getPermission().getSymbol()); Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-rw----")); assertEquals("rw-rw----", finder.find(file).getPermission().getSymbol()); assertEquals(posixAttributes.size(), finder.find(file).getSize()); assertEquals(posixAttributes.lastModifiedTime().toMillis(), finder.find(file).getModificationDate()); assertEquals(posixAttributes.creationTime().toMillis(), finder.find(file).getCreationDate()); assertEquals(posixAttributes.lastAccessTime().toMillis(), finder.find(file).getAccessedDate()); new LocalDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); } }
Example 2
Source File: MCRContentStoreTestCase.java From mycore with GNU General Public License v3.0 | 7 votes |
@Test public void testMD5CopyCommand() throws IOException { MCRObjectID derId = MCRObjectID.getInstance("MCR_derivate_00000003"); String fileName = "hallo.txt"; MCRPath filePath = MCRPath.getPath(derId.toString(), fileName); Files.createFile(filePath); try (InputStream is = new CharSequenceInputStream("Hello World!", StandardCharsets.UTF_8)) { Files.copy(is, filePath, StandardCopyOption.REPLACE_EXISTING); } startNewTransaction(); MCRFileAttributes attrs = Files.readAttributes(filePath, MCRFileAttributes.class); MCRCStoreIFS2 ifs2 = (MCRCStoreIFS2) MCRContentStoreFactory.getStore("IFS2"); MCRFileCollection fileCollection = ifs2.getIFS2FileCollection(derId); org.mycore.datamodel.ifs2.MCRFile file2 = (org.mycore.datamodel.ifs2.MCRFile) fileCollection.getChild(fileName); Assert.assertEquals("MD5 mismatch.", attrs.md5sum(), file2.getMD5()); file2.setMD5("invalid"); file2 = (org.mycore.datamodel.ifs2.MCRFile) fileCollection.getChild(fileName); Assert.assertNotEquals("MD5 was not updated.", attrs.md5sum(), file2.getMD5()); MCRIFSCommands.copyMD5ToIFS2(); file2 = (org.mycore.datamodel.ifs2.MCRFile) fileCollection.getChild(fileName); Assert.assertEquals("MD5 mismatch.", attrs.md5sum(), file2.getMD5()); }
Example 3
Source File: FsBlobContainer.java From crate with Apache License 2.0 | 7 votes |
@Override public Map<String, BlobMetaData> listBlobsByPrefix(String blobNamePrefix) throws IOException { // If we get duplicate files we should just take the last entry Map<String, BlobMetaData> builder = new HashMap<>(); blobNamePrefix = blobNamePrefix == null ? "" : blobNamePrefix; try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, blobNamePrefix + "*")) { for (Path file : stream) { final BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class); if (attrs.isRegularFile()) { builder.put(file.getFileName().toString(), new PlainBlobMetaData(file.getFileName().toString(), attrs.size())); } } } return unmodifiableMap(builder); }
Example 4
Source File: FsBlobContainer.java From Elasticsearch with Apache License 2.0 | 7 votes |
@Override public ImmutableMap<String, BlobMetaData> listBlobsByPrefix(String blobNamePrefix) throws IOException { // using MapBuilder and not ImmutableMap.Builder as it seems like File#listFiles might return duplicate files! MapBuilder<String, BlobMetaData> builder = MapBuilder.newMapBuilder(); blobNamePrefix = blobNamePrefix == null ? "" : blobNamePrefix; try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, blobNamePrefix + "*")) { for (Path file : stream) { final BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class); if (attrs.isRegularFile()) { builder.put(file.getFileName().toString(), new PlainBlobMetaData(file.getFileName().toString(), attrs.size())); } } } return builder.immutableMap(); }
Example 5
Source File: UnixFileAttributeManager.java From yajsync with GNU General Public License v3.0 | 7 votes |
private RsyncFileAttributes cachedStat(Path path) throws IOException { String toStat = "unix:mode,lastModifiedTime,size,uid,gid"; Map<String, Object> attrs = Files.readAttributes(path, toStat, LinkOption.NOFOLLOW_LINKS); int mode = (int) attrs.get("mode"); long mtime = ((FileTime) attrs.get("lastModifiedTime")).to(TimeUnit.SECONDS); long size = (long) attrs.get("size"); int uid = (int) attrs.get("uid"); int gid = (int) attrs.get("gid"); String userName = _userIdToUserName.getOrDefault(uid, _defaultUser.name()); String groupName = _groupIdToGroupName.getOrDefault(gid, _defaultGroup.name()); User user = new User(userName, uid); Group group = new Group(groupName, gid); return new RsyncFileAttributes(mode, size, mtime, user, group); }
Example 6
Source File: BackupEntry.java From todolist with MIT License | 5 votes |
public BackupEntry(Path path) { this.path = path; try { this.fileSize = Files.size(this.path); BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class); this.createdAt = LocalDateTime.ofInstant(attr.creationTime().toInstant(), ZoneId.systemDefault()); } catch (IOException e) { e.printStackTrace(); } }
Example 7
Source File: ModulePath.java From Bytecoder with Apache License 2.0 | 5 votes |
/** * Scans the given directory for packaged or exploded modules. * * @return a map of module name to ModuleReference for the modules found * in the directory * * @throws IOException if an I/O error occurs * @throws FindException if an error occurs scanning the entry or the * directory contains two or more modules with the same name */ private Map<String, ModuleReference> scanDirectory(Path dir) throws IOException { // The map of name -> mref of modules found in this directory. Map<String, ModuleReference> nameToReference = new HashMap<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path entry : stream) { BasicFileAttributes attrs; try { attrs = Files.readAttributes(entry, BasicFileAttributes.class); } catch (NoSuchFileException ignore) { // file has been removed or moved, ignore for now continue; } ModuleReference mref = readModule(entry, attrs); // module found if (mref != null) { // can have at most one version of a module in the directory String name = mref.descriptor().name(); ModuleReference previous = nameToReference.put(name, mref); if (previous != null) { String fn1 = fileName(mref); String fn2 = fileName(previous); throw new FindException("Two versions of module " + name + " found in " + dir + " (" + fn1 + " and " + fn2 + ")"); } } } } return nameToReference; }
Example 8
Source File: StdErrorReporter.java From linstor-server with GNU General Public License v3.0 | 5 votes |
private BasicFileAttributes getAttributes(final Path file) { BasicFileAttributes basicFileAttributes = null; try { basicFileAttributes = Files.readAttributes(file, BasicFileAttributes.class); } catch (IOException ignored) { } return basicFileAttributes; }
Example 9
Source File: FaultyFileSystem.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
@Override public Map<String,Object> readAttributes(Path file, String attributes, LinkOption... options) throws IOException { triggerEx(file, "readAttributes"); return Files.readAttributes(unwrap(file), attributes, options); }
Example 10
Source File: FaultyFileSystem.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@Override public <A extends BasicFileAttributes> A readAttributes(Path file, Class<A> type, LinkOption... options) throws IOException { triggerEx(file, "readAttributes"); return Files.readAttributes(unwrap(file), type, options); }
Example 11
Source File: FilesReadAttributesTest.java From ParallelGit with Apache License 2.0 | 5 votes |
@Test public void readBasicAttributes_theResultShouldContainSpecifiedAttributes() throws IOException { writeToGfs("/file.txt"); Map<String, Object> attributeMap = Files.readAttributes(gfs.getPath("/file.txt"), "basic:size,isRegularFile"); assertTrue(attributeMap.containsKey("size")); assertTrue(attributeMap.containsKey("isRegularFile")); }
Example 12
Source File: EncryptedFileSystemProvider.java From encfs4j with Apache License 2.0 | 4 votes |
@Override public Map<String, Object> readAttributes(Path file, String attributes, LinkOption... options) throws IOException { return Files.readAttributes(EncryptedFileSystem.dismantle(file), attributes, options); }
Example 13
Source File: TestJobServerLogs.java From scheduling with GNU Affero General Public License v3.0 | 4 votes |
private void printDiagnosticMessage() { int LIMIT = 5; System.out.println("This test is going to fail, but before we print diagnostic message." + simpleDateFormat.format(new Date())); // iterate over all files in the 'logsLocation' for (File file : FileUtils.listFiles(new File(logsLocation), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)) { try { BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); System.out.println(String.format("Name: %s, Size: %d, Created: %s, Modified: %s", file.getAbsolutePath(), attr.size(), attr.creationTime(), attr.lastModifiedTime())); BufferedReader br = new BufferedReader(new FileReader(file)); String line; int i; // print up to LIMIT first lines for (i = 0; i < LIMIT && (line = br.readLine()) != null; ++i) { System.out.println(line); } Queue<String> queue = new CircularFifoQueue<>(LIMIT); // reading last LIMIT lines for (; (line = br.readLine()) != null; ++i) { queue.add(line); } if (i >= LIMIT * 2) { // if there is more line than 2*LIMIT System.out.println("......."); System.out.println("....... (skipped content)"); System.out.println("......."); } for (String l : queue) { // print rest of the file System.out.println(l); } System.out.println("------------------------------------"); System.out.println(); } catch (IOException e) { System.out.println("Exception ocurred during accessing file attributes " + e); } } }
Example 14
Source File: MCRRestDerivateContents.java From mycore with GNU General Public License v3.0 | 4 votes |
@HEAD @MCRCacheControl(sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS)) @Operation(description = "get information about mime-type(s), last modified, ETag (md5sum) and ranges support", tags = MCRRestUtils.TAG_MYCORE_FILE, responses = @ApiResponse( description = "Use this for single file metadata queries only. Support is implemented for user agents.", headers = { @Header(name = "Content-Type", description = "mime type of file"), @Header(name = "Content-Length", description = "size of file"), @Header(name = "ETag", description = "MD5 sum of file"), @Header(name = "Last-Modified", description = "last modified date of file"), })) public Response getFileOrDirectoryMetadata() { MCRPath mcrPath = getPath(); MCRFileAttributes fileAttributes; try { fileAttributes = Files.readAttributes(mcrPath, MCRFileAttributes.class); } catch (IOException e) { throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_NOT_FOUND) .withMessage("Could not find file or directory " + mcrPath + ".") .withDetail(e.getMessage()) .withCause(e) .toException(); } if (fileAttributes.isDirectory()) { return Response.ok() .variants(Variant .mediaTypes(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE) .build()) .build(); } String mimeType = context.getMimeType(path); return Response .status(Response.Status.PARTIAL_CONTENT) .header("Accept-Ranges", "bytes") .header(HttpHeaders.CONTENT_TYPE, mimeType) .lastModified(Date.from(fileAttributes.lastModifiedTime().toInstant())) .header(HttpHeaders.CONTENT_LENGTH, fileAttributes.size()) .tag(getETag(fileAttributes)) .build(); }
Example 15
Source File: MCRTileServlet.java From mycore with GNU General Public License v3.0 | 4 votes |
/** * Extracts tile or image properties from iview2 file and transmits it. * * Uses {@link HttpServletRequest#getPathInfo()} (see {@link #getTileInfo(String)}) to get tile attributes. * Also uses {@link #MAX_AGE} to tell the client how long it could cache the information. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final MCRTileInfo tileInfo = getTileInfo(getPathInfo(req)); Path iviewFile = TFP.getTileFile(tileInfo).orElse(null); if(iviewFile==null) { LOGGER.info("TileFile not found: " + tileInfo); return; } if (!Files.exists(iviewFile)) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File does not exist: " + iviewFile); return; } try (FileSystem iviewFS = MCRIView2Tools.getFileSystem(iviewFile)) { Path root = iviewFS.getRootDirectories().iterator().next(); Path tilePath = root.resolve(tileInfo.getTile()); BasicFileAttributes fileAttributes; try { fileAttributes = Files.readAttributes(tilePath, BasicFileAttributes.class); } catch (IOException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Tile not found: " + tileInfo); return; } resp.setHeader("Cache-Control", "max-age=" + MAX_AGE); resp.setDateHeader("Last-Modified", fileAttributes.lastModifiedTime().toMillis()); if (tileInfo.getTile().endsWith("xml")) { resp.setContentType("text/xml"); } else { resp.setContentType("image/jpeg"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Extracting {} size {}", tilePath, fileAttributes.size()); } //size of a tile or imageinfo.xml file is always smaller than Integer.MAX_VALUE resp.setContentLength((int) fileAttributes.size()); try (ServletOutputStream out = resp.getOutputStream()) { Files.copy(tilePath, out); } } LOGGER.debug("Ending MCRTileServlet"); }
Example 16
Source File: JavaIoFileSystem.java From bazel with Apache License 2.0 | 4 votes |
/** * 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 File: PreserveFilters.java From ecs-sync with Apache License 2.0 | 4 votes |
@Override public void filter(ObjectContext objectContext) { File file = (File) objectContext.getObject().getProperty(AbstractFilesystemStorage.PROP_FILE); if (file == null) throw new RuntimeException("could not get source file"); ObjectMetadata metadata = objectContext.getObject().getMetadata(); boolean link = AbstractFilesystemStorage.TYPE_LINK.equals(metadata.getContentType()); BasicFileAttributes basicAttr = readAttributes(file, link); PosixFileAttributes posixAttr = null; if (basicAttr instanceof PosixFileAttributes) posixAttr = (PosixFileAttributes) basicAttr; long mtime = basicAttr.lastModifiedTime().toMillis(); long atime = basicAttr.lastAccessTime() != null ? basicAttr.lastAccessTime().toMillis() : 0; long crtime = basicAttr.creationTime() != null ? basicAttr.creationTime().toMillis() : 0; // preserve file times metadata.setUserMetadataValue(META_MTIME, String.format("%d.%d", mtime / 1000, (mtime % 1000) / 10)); if (atime != 0) metadata.setUserMetadataValue(META_ATIME, String.format("%d.%d", atime / 1000, (atime % 1000) / 10)); if (crtime != 0) metadata.setUserMetadataValue(META_CRTIME, String.format("%d.%d", crtime / 1000, (crtime % 1000) / 10)); // preserve POSIX ACL if (posixAttr != null) { if (posixAttr.owner() != null) metadata.setUserMetadataValue(OLD_META_POSIX_OWNER, posixAttr.owner().getName()); if (posixAttr.group() != null) metadata.setUserMetadataValue(OLD_META_POSIX_GROUP_OWNER, posixAttr.group().getName()); // NOTE: this won't get sticky bit, etc. (we try to get that below) metadata.setUserMetadataValue(META_PERMISSIONS, getOctalMode(posixAttr.permissions())); // *try* to get uid/gid/ctime/mode too (this will override owner/group-owner/permissions) try { LinkOption[] options = link ? new LinkOption[]{LinkOption.NOFOLLOW_LINKS} : new LinkOption[0]; Map<String, Object> attrs = Files.readAttributes(file.toPath(), "unix:uid,gid,ctime,mode", options); Integer uid = (Integer) attrs.get("uid"); Integer gid = (Integer) attrs.get("gid"); long ctime = attrs.get("ctime") != null ? ((FileTime) attrs.get("ctime")).toMillis() : 0; Integer mode = (Integer) attrs.get("mode"); if (uid != null) metadata.setUserMetadataValue(META_OWNER, uid.toString()); if (gid != null) metadata.setUserMetadataValue(META_GROUP, gid.toString()); if (ctime != 0) metadata.setUserMetadataValue(META_CTIME, String.format("%d.%d", ctime / 1000, (ctime % 1000) / 10)); // only want last 4 octals (not sure why there are more in some cases) if (mode != null) metadata.setUserMetadataValue(META_PERMISSIONS, String.format("%04o", mode & 07777)); } catch (IOException e) { log.warn("could not get uid/gid/ctime/mode", e); } } getNext().filter(objectContext); }
Example 18
Source File: LocalFileSystem.java From xenon with Apache License 2.0 | 4 votes |
PathAttributes getLocalFileAttributes(Path p, java.nio.file.Path path) throws XenonException { try { PathAttributesImplementation result = new PathAttributesImplementation(); result.setPath(p); result.setExecutable(Files.isExecutable(path)); result.setReadable(Files.isReadable(path)); result.setReadable(Files.isWritable(path)); boolean isWindows = LocalFileSystemUtils.isWindows(); BasicFileAttributes basicAttributes; if (isWindows) { // The Files.isHidden seems to fail in Windows, so we directly set it to false. result.setHidden(false); // These should always work. basicAttributes = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); } else { result.setHidden(Files.isHidden(path)); // Note: when in a posix environment, basicAttributes point to // posixAttributes. java.nio.file.attribute.PosixFileAttributes posixAttributes = Files.readAttributes(path, java.nio.file.attribute.PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); basicAttributes = posixAttributes; result.setOwner(posixAttributes.owner().getName()); result.setGroup(posixAttributes.group().getName()); result.setPermissions(xenonPermissions(posixAttributes.permissions())); } result.setCreationTime(basicAttributes.creationTime().toMillis()); result.setLastAccessTime(basicAttributes.lastAccessTime().toMillis()); result.setLastModifiedTime(basicAttributes.lastModifiedTime().toMillis()); result.setDirectory(basicAttributes.isDirectory()); result.setRegular(basicAttributes.isRegularFile()); result.setSymbolicLink(basicAttributes.isSymbolicLink()); result.setOther(basicAttributes.isOther()); if (result.isRegular()) { result.setSize(basicAttributes.size()); } return result; } catch (IOException e) { throw new XenonException(ADAPTOR_NAME, "Cannot read attributes.", e); } }
Example 19
Source File: PathInfo.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 4 votes |
public PathInfo(Path path) throws IOException { this(path, Files.readAttributes(path, BasicFileAttributes.class)); }
Example 20
Source File: IsFileDirectory.java From levelup-java-examples with Apache License 2.0 | 3 votes |
@Test public void file_is_directory_nio() throws IOException { BasicFileAttributes attr = Files.readAttributes(source, BasicFileAttributes.class); boolean isFileADirectory = attr.isDirectory(); assertTrue(isFileADirectory); }