下面列出了怎么用java.nio.file.attribute.PosixFileAttributes的API类实例代码及写法,或者点击链接到github查看源代码。
@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());
}
}
Map<UnixSshPath, PosixFileAttributes> statDirectory( UnixSshPath directoryPath ) throws IOException {
Map<UnixSshPath, PosixFileAttributes> map = new HashMap<>();
SupportedAttribute[] allAttributes = SupportedAttribute.values();
String command = directoryPath.getFileSystem().getCommand( "find" ) + " "
+ directoryPath.toAbsolutePath().quotedString()
+ " -maxdepth 1 -type f -exec " + statCommand( directoryPath, allAttributes, true ) + " {} +";
String stdout = executeForStdout( directoryPath, command );
if ( stdout.length() > 0 ) {
String[] results = stdout.split( "\n" );
for ( String file : results ) {
logger.trace( "parsing stat response for {}", file );
Map<String, Object> fileAttributes = statParse( file, allAttributes );
UnixSshPath filePath = directoryPath.toAbsolutePath().relativize( directoryPath.resolve(
(String)fileAttributes.get( SupportedAttribute.name.toString() ) ) );
map.put( filePath, new PosixFileAttributesImpl( fileAttributes ) );
}
}
logger.trace( "returning map" );
return map;
}
@SuppressWarnings("unchecked")
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path,
Class<A> type, LinkOption... options)
throws IOException {
if (type == BasicFileAttributes.class ||
type == HadoopBasicFileAttributes.class) {
return (A) toHadoopPath(path).getAttributes();
}
if (type == PosixFileAttributes.class) {
return (A) toHadoopPath(path).getPosixAttributes();
}
throw new UnsupportedOperationException("readAttributes:" + type.getName());
}
@Test
public void testReadAttributesFileFollowLinks() throws IOException {
Path foo = addFile("/foo");
setContents(foo, new byte[1024]);
PosixFileAttributes attributes = fileSystem.readAttributes(createPath("/foo"));
assertEquals(Files.size(foo), attributes.size());
assertNotNull(attributes.owner().getName());
assertNotNull(attributes.group().getName());
assertNotNull(attributes.permissions());
assertFalse(attributes.isDirectory());
assertTrue(attributes.isRegularFile());
assertFalse(attributes.isSymbolicLink());
assertFalse(attributes.isOther());
}
@Test
public void testReadAttributesFileNoFollowLinks() throws IOException {
Path foo = addFile("/foo");
setContents(foo, new byte[1024]);
PosixFileAttributes attributes = fileSystem.readAttributes(createPath("/foo"), LinkOption.NOFOLLOW_LINKS);
assertEquals(Files.size(foo), attributes.size());
assertNotNull(attributes.owner().getName());
assertNotNull(attributes.group().getName());
assertNotNull(attributes.permissions());
assertFalse(attributes.isDirectory());
assertTrue(attributes.isRegularFile());
assertFalse(attributes.isSymbolicLink());
assertFalse(attributes.isOther());
}
@Test
public void testReadAttributesSymLinkToFileFollowLinks() throws IOException {
Path foo = addFile("/foo");
setContents(foo, new byte[1024]);
Path bar = addSymLink("/bar", foo);
PosixFileAttributes attributes = fileSystem.readAttributes(createPath("/bar"));
long sizeOfFoo = Files.readAttributes(foo, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS).size();
long sizeOfBar = Files.readAttributes(bar, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS).size();
assertEquals(sizeOfFoo, attributes.size());
assertNotEquals(sizeOfBar, attributes.size());
assertNotNull(attributes.owner().getName());
assertNotNull(attributes.group().getName());
assertNotNull(attributes.permissions());
assertFalse(attributes.isDirectory());
assertTrue(attributes.isRegularFile());
assertFalse(attributes.isSymbolicLink());
assertFalse(attributes.isOther());
}
@Test
public void testReadAttributesSymLinkToFileNoFollowLinks() throws IOException {
Path foo = addFile("/foo");
setContents(foo, new byte[1024]);
Path bar = addSymLink("/bar", foo);
PosixFileAttributes attributes = fileSystem.readAttributes(createPath("/bar"), LinkOption.NOFOLLOW_LINKS);
long sizeOfFoo = Files.readAttributes(foo, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS).size();
long sizeOfBar = Files.readAttributes(bar, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS).size();
assertEquals(sizeOfBar, attributes.size());
assertNotEquals(sizeOfFoo, attributes.size());
assertNotNull(attributes.owner().getName());
assertNotNull(attributes.group().getName());
assertNotNull(attributes.permissions());
assertFalse(attributes.isDirectory());
assertFalse(attributes.isRegularFile());
assertTrue(attributes.isSymbolicLink());
assertFalse(attributes.isOther());
}
@Test
public void testReadAttributesSymLinkToDirectoryFollowLinks() throws IOException {
Path foo = addDirectory("/foo");
addSymLink("/bar", foo);
PosixFileAttributes attributes = fileSystem.readAttributes(createPath("/bar"));
long sizeOfFoo = Files.readAttributes(foo, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS).size();
// on Windows, foo and bar have the same sizes
assertEquals(sizeOfFoo, attributes.size());
assertNotNull(attributes.owner().getName());
assertNotNull(attributes.group().getName());
assertNotNull(attributes.permissions());
assertTrue(attributes.isDirectory());
assertFalse(attributes.isRegularFile());
assertFalse(attributes.isSymbolicLink());
assertFalse(attributes.isOther());
}
@Test
public void testReadAttributesSymLinkToDirectoryNoFollowLinks() throws IOException {
Path foo = addDirectory("/foo");
Path bar = addSymLink("/bar", foo);
PosixFileAttributes attributes = fileSystem.readAttributes(createPath("/bar"), LinkOption.NOFOLLOW_LINKS);
long sizeOfBar = Files.readAttributes(bar, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS).size();
// on Windows, foo and bar have the same sizes
assertEquals(sizeOfBar, attributes.size());
assertNotNull(attributes.owner().getName());
assertNotNull(attributes.group().getName());
assertNotNull(attributes.permissions());
assertFalse(attributes.isDirectory());
assertFalse(attributes.isRegularFile());
assertTrue(attributes.isSymbolicLink());
assertFalse(attributes.isOther());
}
/** {@inheritDoc} */
@Override public IgfsFile info(final IgfsPath path) {
File file = fileForPath(path);
if (!file.exists())
return null;
boolean isDir = file.isDirectory();
PosixFileAttributes attrs = LocalFileSystemUtils.posixAttributes(file);
Map<String, String> props = LocalFileSystemUtils.posixAttributesToMap(attrs);
BasicFileAttributes basicAttrs = LocalFileSystemUtils.basicAttributes(file);
if (isDir) {
return new LocalFileSystemIgfsFile(path, false, true, 0,
basicAttrs.lastAccessTime().toMillis(), basicAttrs.lastModifiedTime().toMillis(), 0, props);
}
else {
return new LocalFileSystemIgfsFile(path, file.isFile(), false, 0,
basicAttrs.lastAccessTime().toMillis(), basicAttrs.lastModifiedTime().toMillis(), file.length(), props);
}
}
/**
* Get POSIX attributes for file.
*
* @param file File.
* @return PosixFileAttributes.
*/
@Nullable public static PosixFileAttributes posixAttributes(File file) {
PosixFileAttributes attrs = null;
try {
PosixFileAttributeView view = Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class);
if (view != null)
attrs = view.readAttributes();
}
catch (IOException e) {
throw new IgfsException("Failed to read POSIX attributes: " + file.getAbsolutePath(), e);
}
return attrs;
}
@Override
public RsyncFileAttributes stat(Path path) throws IOException
{
PosixFileAttributes attrs = Files.readAttributes(path, PosixFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
UserPrincipal userPrincipal = attrs.owner();
String userName = userPrincipal.getName();
GroupPrincipal groupPrincipal = attrs.group();
String groupName = groupPrincipal.getName();
_nameToUserPrincipal.putIfAbsent(userName, userPrincipal);
_nameToGroupPrincipal.putIfAbsent(groupName, groupPrincipal);
return new RsyncFileAttributes(toMode(attrs),
attrs.size(),
attrs.lastModifiedTime().to(TimeUnit.SECONDS),
new User(userName, _defaultUserId),
new Group(groupName, _defaultGroupId));
}
private static int getPosixFileMode(Path file) throws IOException {
final PosixFileAttributes attr = Files.readAttributes(file, PosixFileAttributes.class);
final Set<PosixFilePermission> perm = attr.permissions();
// retain permissions, note these values are octal
//noinspection OctalInteger
int mode = 0100000;
//noinspection OctalInteger
mode += 0100 * getModeFromPermissions(
perm.contains(PosixFilePermission.OWNER_READ),
perm.contains(PosixFilePermission.OWNER_WRITE),
perm.contains(PosixFilePermission.OWNER_EXECUTE));
//noinspection OctalInteger
mode += 010 * getModeFromPermissions(
perm.contains(PosixFilePermission.GROUP_READ),
perm.contains(PosixFilePermission.GROUP_WRITE),
perm.contains(PosixFilePermission.GROUP_EXECUTE));
mode += getModeFromPermissions(
perm.contains(PosixFilePermission.OTHERS_READ),
perm.contains(PosixFilePermission.OTHERS_WRITE),
perm.contains(PosixFilePermission.OTHERS_EXECUTE));
return mode;
}
@Test
public void testToAndFromJSON() throws IOException {
KnoxShellTable table = new KnoxShellTable();
table.header("Column A").header("Column B").header("Column C");
table.row().value("123").value("456").value("344444444");
table.row().value("789").value("012").value("844444444");
String json = table.toJSON();
KnoxShellTable table2 = KnoxShellTable.builder().json().fromJson(json);
assertEquals(table.toString(), table2.toString());
final Path jsonPath = Paths.get(testFolder.newFolder().getAbsolutePath(), "testJson.json");
table.toJSON(jsonPath.toString());
final PosixFileAttributes jsonPathAttributes = Files.readAttributes(jsonPath, PosixFileAttributes.class);
assertEquals("rw-------", PosixFilePermissions.toString(jsonPathAttributes.permissions()));
KnoxShellTable table3 = KnoxShellTable.builder().json().path(jsonPath.toString());
assertEquals(table.toString(), table3.toString());
}
@Test
public void getGroupOfFile_shouldReturnNull() throws IOException {
writeToCache("/file.txt");
commitToMaster();
initGitFileSystem();
PosixFileAttributes attributes = readPosixAttributes("/file.txt");
assertNull(attributes.group());
}
public int getUnixMode(File file) {
try {
final PosixFileAttributes posixFileAttributes = Files.readAttributes(file.toPath(), PosixFileAttributes.class);
return convertToInt(posixFileAttributes.permissions());
}catch (Exception e) {
throw new NativeIntegrationException(String.format("Failed to read File permissions for %s", file.getAbsolutePath()), e);
}
}
@Test
public void getPermissionOfFile_shouldNotContainOwnerExecute() throws IOException {
writeToCache("/file.txt");
commitToMaster();
initGitFileSystem();
PosixFileAttributes attributes = readPosixAttributes("/file.txt");
Collection permissions = (Collection) attributes.permissions();
assertFalse(permissions.contains(OWNER_EXECUTE));
}
public static void main(String[] args) {
// regular file
Path path = Paths.get("resources/lorem-ipsum.txt");
// as example for file type
// create a named pipe: 'mknod /tmp/named.pipe p'
// Path path = Paths.get("/tmp/named.pipe");
try {
System.out.printf("### single access to file attributes%n");
PosixFileAttributes attr;
attr = Files.readAttributes(path, PosixFileAttributes.class, NOFOLLOW_LINKS);
String outFormat = "%-20s: %s%n";
System.out.printf(outFormat, "creationTime", attr.creationTime());
System.out.printf(outFormat, "lastAccessTime", attr.lastAccessTime());
System.out.printf(outFormat, "lastModifiedTime", attr.lastModifiedTime());
System.out.printf(outFormat, "isRegularFile", attr.isRegularFile());
System.out.printf(outFormat, "isDirectory", attr.isDirectory());
System.out.printf(outFormat, "isSymbolicLink", attr.isSymbolicLink());
// could be a named pipe for example
System.out.printf(outFormat, "isOther", attr.isOther());
System.out.printf(outFormat, "size", attr.size());
// object which uniquely identifies the given file
// on UNIX: it contains the device id and the inode
System.out.printf(outFormat, "fileKey", attr.fileKey());
System.out.printf(outFormat, "owner", attr.owner());
System.out.printf(outFormat, "group", attr.group());
System.out.printf(outFormat, "permissons", attr.permissions());
System.out.printf("%n### bulk access to file attributes%n");
Map<String, Object> attrBulk;
attrBulk = Files.readAttributes(path, "posix:*", NOFOLLOW_LINKS);
for (String key : attrBulk.keySet()) {
System.out.printf("%s:%-16s: %s%n", "posix", key, attrBulk.get(key));
}
} catch (IOException ex) {
System.err.println("failed to obtain PosixFileAttributes " + ex.getMessage());
}
}
/**
* Validate that the Zip file permissions are as expected after updating the
* Zip file
* @param newPerms The permissions to set on the Zip File before updating the
* file
* @throws Exception If an error occurs
*/
@Test(dataProvider = "posixPermissions")
public void testZipPerms(Set<PosixFilePermission> newPerms) throws Exception {
if (DEBUG) {
System.out.printf("Test Run with perms= %s%n", newPerms);
}
PosixFileAttributes attrs = getPosixAttributes(zipFile);
// Permissions used to verify the results of updating the Zip file
if (newPerms == null) {
// Use current Zip File permissions;
newPerms = attrs.permissions();
}
displayPermissions("Original permissions", zipFile);
// Now set the new permissions
Files.setPosixFilePermissions(zipFile, newPerms);
displayPermissions("Revised permissions", zipFile);
// Update the Zip file
zip(zipFile, Collections.emptyMap(), entry1);
// Validate that the permissions are as expected after updating the
// Zip file
PosixFileAttributes afterAttrs = getPosixAttributes(zipFile);
displayPermissions("Permissions after updating the Zip File", zipFile);
assertEquals(afterAttrs.permissions(), newPerms,
"Permissions were not updated as expected!");
}
@Override
@SuppressWarnings("unchecked")
public <A extends BasicFileAttributes> A readAttributes( Path path, Class<A> type, LinkOption... linkOptions ) throws IOException {
if ( type == BasicFileAttributes.class ) {
return (A)new BasicFileAttributesImpl( path, linkOptions );
}
if ( type == PosixFileAttributes.class ) {
return (A)new PosixFileAttributesImpl( path, linkOptions );
}
if ( type == null ) {
throw new NullPointerException();
}
return (A)null;
}
/**
* Returns a file's POSIX file attributes.
*
* @param path The path to the Zip file
* @return The POSIX file attributes for the specified file or
* null if the POSIX attribute view is not available
* @throws IOException If an error occurs obtaining the POSIX attributes for
* the specified file
*/
public PosixFileAttributes getPosixAttributes(Path path) throws IOException {
PosixFileAttributes attrs = null;
PosixFileAttributeView view =
Files.getFileAttributeView(path, PosixFileAttributeView.class);
// Return if the attribute view is not supported
if (view == null) {
return null;
}
attrs = view.readAttributes();
return attrs;
}
/**
* 设置文件权限。前提:必须支持PosixFileAttributeView.
*/
public static void setFilePerm(File file, String perm) {
if (filePermSupported()) {
try {
Set<PosixFilePermission> perms = PosixFilePermissions.fromString(perm);
PosixFileAttributes attr = Files.readAttributes(file.toPath(), PosixFileAttributes.class);
attr.permissions().clear();
Files.setPosixFilePermissions(file.toPath(), perms);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
/**
*
* @param filename the file name
* @return the file owner
* @throws FileSystemOperationException
*/
private String getOwner(
String filename ) {
try {
UserPrincipal owner = Files.readAttributes(new File(filename).toPath(),
PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
.owner();
return owner.getName();
} catch (Exception e) {
throw new FileSystemOperationException("Could not get owner for '" + filename + "'", e);
}
}
/**
*
* @param filename the file name
* @return the file group name
* @throws FileSystemOperationException
*/
private String getGroup(
String filename ) {
try {
GroupPrincipal group = Files.readAttributes(new File(filename).toPath(),
PosixFileAttributes.class,
LinkOption.NOFOLLOW_LINKS)
.group();
return group.getName();
} catch (Exception e) {
throw new FileSystemOperationException("Could not get group for '" + filename + "'", e);
}
}
protected PathAttributes convert(final java.nio.file.Path file) throws IOException {
final boolean isPosix = session.isPosixFilesystem();
final PathAttributes attributes = new PathAttributes();
final Class<? extends BasicFileAttributes> provider = isPosix ? PosixFileAttributes.class : DosFileAttributes.class;
final BasicFileAttributes a = Files.readAttributes(file, provider, LinkOption.NOFOLLOW_LINKS);
if(a.isRegularFile()) {
attributes.setSize(a.size());
}
attributes.setModificationDate(a.lastModifiedTime().toMillis());
attributes.setCreationDate(a.creationTime().toMillis());
attributes.setAccessedDate(a.lastAccessTime().toMillis());
if(isPosix) {
attributes.setOwner(((PosixFileAttributes) a).owner().getName());
attributes.setGroup(((PosixFileAttributes) a).group().getName());
attributes.setPermission(new Permission(PosixFilePermissions.toString(((PosixFileAttributes) a).permissions())));
}
else {
Permission.Action actions = Permission.Action.none;
if(Files.isReadable(file)) {
actions = actions.or(Permission.Action.read);
}
if(Files.isWritable(file)) {
actions = actions.or(Permission.Action.write);
}
if(Files.isExecutable(file)) {
actions = actions.or(Permission.Action.execute);
}
attributes.setPermission(new Permission(
actions, Permission.Action.none, Permission.Action.none
));
}
return attributes;
}
@Test
public void testAttributes() {
PosixFileAttributes attrs = provider.readAttributes(file);
assertThat(attrs.permissions()).isEqualTo(PosixFilePermissions.fromString("rw-r--r--"));
assertThat(attrs.group()).isEqualTo(createGroupPrincipal("group"));
assertThat(attrs.fileKey()).isEqualTo(0);
}
public static PosixFileAttributes posixStatNullable(Path path, boolean followSymlinks) {
try {
return Files.readAttributes(path, PosixFileAttributes.class, linkOpts(followSymlinks));
} catch (IOException e) {
return null;
}
}
static final String getFileAttributes(File file) {
try {
PosixFileAttributes attrs = Files.getFileAttributeView(
file.toPath(), PosixFileAttributeView.class, new LinkOption[0]).readAttributes();
String s = String.format("%s: %s %s %s%n",
file.getPath(),
attrs.owner().getName(),
attrs.group().getName(),
PosixFilePermissions.toString(attrs.permissions()));
return s;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
PosixFileAttributes getPosixFileAttributes(HadoopPath path) throws IOException
{
beginRead();
try {
ensureOpen();
org.apache.hadoop.fs.Path resolvedPath = path.getRawResolvedPath();
FileStatus fileStatus = path.getFileSystem().getHDFS().getFileStatus(resolvedPath);
String fileKey = resolvedPath.toString();
return new HadoopPosixFileAttributes(this, fileKey, fileStatus);
} finally {
endRead();
}
}
@VisibleForTesting
void loadPermissionInfoByNonNativeIO() {
IOException e = null;
try {
java.nio.file.Path path = Paths.get(getPath().toUri());
String permission = '-' + PosixFilePermissions.toString(Files.getPosixFilePermissions(path));
setPermission(FsPermission.valueOf(permission));
String owner = Files.getOwner(path).getName();
String group = Files.readAttributes(path, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS).group().getName();
// If on windows domain, token format is DOMAIN\\user and we want to
// extract only the user name
// same as to the group name
if (Shell.WINDOWS) {
owner = removeDomain(owner);
group = removeDomain(group);
}
setOwner(owner);
setGroup(group);
} catch (IOException ioe) {
e = ioe;
} finally {
if (e != null) {
throw new RuntimeException("Error while running command to get " +
"file permissions : " +
StringUtils.stringifyException(e));
}
}
}