當前位置: 首頁>>代碼示例>>Java>>正文


Java PosixFileAttributes類代碼示例

本文整理匯總了Java中java.nio.file.attribute.PosixFileAttributes的典型用法代碼示例。如果您正苦於以下問題:Java PosixFileAttributes類的具體用法?Java PosixFileAttributes怎麽用?Java PosixFileAttributes使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


PosixFileAttributes類屬於java.nio.file.attribute包,在下文中一共展示了PosixFileAttributes類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: setFilePerm

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
/**
 * 設置文件權限。前提:必須支持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);
    }
  }
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:16,代碼來源:FilePerm.java

示例2: testConvert

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
@Test
public void testConvert() throws Exception {
    final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
    if(session.isPosixFilesystem()) {
        session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
        session.login(new DisabledPasswordStore(), 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());
    }
}
 
開發者ID:iterate-ch,項目名稱:cyberduck,代碼行數:26,代碼來源:LocalAttributesFinderFeatureTest.java

示例3: getFileListEntry

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
private static String getFileListEntry(File fileInDir) {

        StringBuilder sb = new StringBuilder();
        try {
            PosixFileAttributes fa = Files.readAttributes(fileInDir.toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
            sb.append(fa.isDirectory() ? "d" : fa.isSymbolicLink() ? "l" : fa.isRegularFile() ? "f" : "-");
            sb.append(fileInDir.canRead() ? "r" : "-");
            sb.append(fileInDir.canWrite() ? "w" : "-");
            sb.append(fileInDir.canExecute() ? "x" : "-");
            sb.append("\t");
            sb.append(fa.owner());
            sb.append(fa.owner().getName().length() < 4 ? "\t\t" : "\t");
            sb.append(fa.group());
            sb.append(fa.group().getName().length() < 4 ? "\t\t" : "\t");
            sb.append(fa.size());
            sb.append(String.valueOf(fa.size()).length() < 4 ? "\t\t" : "\t");
            sb.append(fa.lastModifiedTime().toString());
            sb.append("\t");
            sb.append(fa.isDirectory() ? fileInDir.getName() + "/" : fileInDir.getName());
        } catch (IOException e) {
            logger.log(Level.WARNING, "Failed to get file attributes", e);
        }
        logger.info(sb.toString());
        return sb.toString();
    }
 
開發者ID:fast-data-transfer,項目名稱:fdt,代碼行數:26,代碼來源:FDTSession.java

示例4: resetFileAttributes

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
private int resetFileAttributes(Context context, FileState fileState, Path file) throws IOException {
    boolean attributesModified = false;

    try {
        BasicFileAttributes attributes;

        if (SystemUtils.IS_OS_WINDOWS) {
            DosFileAttributes dosFileAttributes = Files.readAttributes(file, DosFileAttributes.class);
            attributes = dosFileAttributes;

            attributesModified = resetDosPermissions(context, file, fileState, dosFileAttributes) || attributesModified;
        } else {
            PosixFileAttributes posixFileAttributes = Files.readAttributes(file, PosixFileAttributes.class);
            attributes = posixFileAttributes;

            attributesModified = resetPosixPermissions(file, fileState, posixFileAttributes) || attributesModified;
        }

        attributesModified = resetCreationTime(file, fileState, attributes) || attributesModified;
        attributesModified = resetLastModified(file, fileState, attributes) || attributesModified;
        attributesModified = resetSELinux(context, file, fileState) || attributesModified;
    } catch (Exception ex) {
        Logger.error(ex.getMessage());
    }
    return attributesModified ? 1 : 0;
}
 
開發者ID:evrignaud,項目名稱:fim,代碼行數:27,代碼來源:ResetFileAttributesCommand.java

示例5: info

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
/** {@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);
    }
}
 
開發者ID:apache,項目名稱:ignite,代碼行數:25,代碼來源:LocalIgfsSecondaryFileSystem.java

示例6: posixAttributes

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:apache,項目名稱:ignite,代碼行數:22,代碼來源:LocalFileSystemUtils.java

示例7: constructCrawlBundle

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
private void constructCrawlBundle(Path src, Path dest) throws IOException {
	Path zipFile = dest.resolve("crawl-bundle.zip");
	try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(zipFile))) {
		Files.walk(src)
				.filter(ImportJob::shouldIncludeInCrawlBundle)
				.forEachOrdered((path) -> {
					ZipEntry entry = new ZipEntry(src.relativize(path).toString());
					try {
						PosixFileAttributes attr = Files.readAttributes(path, PosixFileAttributes.class);
						entry.setCreationTime(attr.creationTime());
						entry.setLastModifiedTime(attr.lastModifiedTime());
						entry.setLastAccessTime(attr.lastAccessTime());
						entry.setSize(attr.size());
						zip.putNextEntry(entry);
						Files.copy(path, zip);
					} catch (IOException e) {
						throw new UncheckedIOException(e);
					}
				});
	}
}
 
開發者ID:nla,項目名稱:bamboo,代碼行數:22,代碼來源:ImportJob.java

示例8: stat

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
@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));
}
 
開發者ID:perlundq,項目名稱:yajsync,代碼行數:18,代碼來源:PosixFileAttributeManager.java

示例9: getPosixAttributesString

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
/**
 * @param path
 * @return
 */
public static String getPosixAttributesString(Path path) {
    PosixFileAttributeView posixView = Files.getFileAttributeView(path, PosixFileAttributeView.class);
    StringBuilder attrs = new StringBuilder();

    try {
        // + all basic attributes
        PosixFileAttributes posixAttrs = posixView.readAttributes();

        if (posixAttrs != null) {
            attrs.append(PosixFilePermissions.toString(posixAttrs.permissions()));
        }
    }
    catch (IOException e) {
        log.warn("unable to read Posix file attributes.", e); //$NON-NLS-1$
    }
    return attrs.toString();
}
 
開發者ID:e4c,項目名稱:EclipseCommander,代碼行數:22,代碼來源:PathUtils.java

示例10: readAttributes

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
@Override
public Map<String, Object> readAttributes(String attributes,
    LinkOption[] options) throws IOException {
  PosixFileAttributes zfas = readAttributes();
  LinkedHashMap<String, Object> map = new LinkedHashMap<>();
  if ("*".equals(attributes)) {
    for (AttrID id : AttrID.values()) {
      map.put(id.name(), attribute(id, zfas));
    }
  } else {
    String[] as = attributes.split(",");
    for (String a : as) {
      map.put(a, attribute(AttrID.valueOf(a), zfas));
    }
  }
  return map;
}
 
開發者ID:damiencarol,項目名稱:jsr203-hadoop,代碼行數:18,代碼來源:HadoopPosixFileAttributeView.java

示例11: readAttributes

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
@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());
}
 
開發者ID:damiencarol,項目名稱:jsr203-hadoop,代碼行數:18,代碼來源:HadoopFileSystemProvider.java

示例12: UnixBuilder

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
public UnixBuilder( FSDescription descr, T t ) {
        super( descr, t );

        PathLimits pathLimits = new PathLimits( OS.UNIX );
        PathSpec pathSpec = new PathSpecUnix();

        descr.props.put( Tests10PathWithContent.ONE_CHAR_COUNT, pathLimits.getBigChar() );
        descr.props.put( Tests10PathWithContent.MAX_FILENAME_LENGTH, pathSpec.getMaxFilenameLength() );
        descr.props.put( Tests10PathWithContent.MAX_PATH_LENGTH, pathSpec.getMaxPathLength() );
        descr.props.put( Tests10PathWithContent.GET_FILENAME_LENGTH, (Function<String,Integer>)pathSpec::getFilenameLength );
        descr.props.put( Tests10PathWithContent.GET_PATH_LENGTH, (Function<String,Integer>)pathSpec::getPathLength );


//        descr.removeTopic( LimitedPath.class ); theory but linux c limits
        descr.removeTopic( Windows.class );
        descr.removeTopic( DosAttributesT.class );
        descr.removeTopic( CaseInsensitive.class );
        descr.removeTopic( NonCasePreserving.class );

        descr.attributeDescriptions.put( "posix", attributeBuilding( Posix.class, "posix", PosixFileAttributeView.class, PosixFileAttributes.class ).
                addAttribute( "owner", PosixFileAttributes::owner ).
                addAttribute( "permissions", PosixFileAttributes::permissions ).
                addAttribute( "group", PosixFileAttributes::group ).
                build());

    }
 
開發者ID:openCage,項目名稱:niotest,代碼行數:27,代碼來源:UnixBuilder.java

示例13: testCreateReadOnlyFileSetsPermissions

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
@Test
public void testCreateReadOnlyFileSetsPermissions() throws IOException {
  Path path = Paths.get("hello.txt");
  ImmutableSet<PosixFilePermission> permissions =
    ImmutableSet.<PosixFilePermission>of(
        PosixFilePermission.OWNER_READ,
        PosixFilePermission.GROUP_READ,
        PosixFilePermission.OTHERS_READ);

  filesystem.writeContentsToPath(
      "hello world",
      path,
      PosixFilePermissions.asFileAttribute(permissions));
  // The umask may restrict the actual permissions on the filesystem:
  // https://fburl.com/26569549
  // So the best we can do is to check that the actual permissions are a
  // strict subset of the expected permissions.
  PosixFileAttributes attrs = filesystem.readAttributes(path, PosixFileAttributes.class);
  assertTrue(permissions.containsAll(attrs.permissions()));
}
 
開發者ID:saleehk,項目名稱:buck-cutom,代碼行數:21,代碼來源:ProjectFilesystemTest.java

示例14: testCreateReadOnlyFileSetsPermissions

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
@Test
public void testCreateReadOnlyFileSetsPermissions() throws IOException {
  Assume.assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));
  Path path = Paths.get("hello.txt");
  ImmutableSet<PosixFilePermission> permissions =
      ImmutableSet.of(
          PosixFilePermission.OWNER_READ,
          PosixFilePermission.GROUP_READ,
          PosixFilePermission.OTHERS_READ);

  filesystem.writeContentsToPath(
      "hello world", path, PosixFilePermissions.asFileAttribute(permissions));
  // The umask may restrict the actual permissions on the filesystem:
  // https://fburl.com/26569549
  // So the best we can do is to check that the actual permissions are a
  // strict subset of the expected permissions.
  PosixFileAttributes attrs = filesystem.readAttributes(path, PosixFileAttributes.class);
  assertTrue(permissions.containsAll(attrs.permissions()));
}
 
開發者ID:facebook,項目名稱:buck,代碼行數:20,代碼來源:DefaultProjectFilesystemTest.java

示例15: installConfig

import java.nio.file.attribute.PosixFileAttributes; //導入依賴的package包/類
/**
 * Copies the files from {@code tmpConfigDir} into {@code destConfigDir}.
 * Any files existing in both the source and destination will be skipped.
 */
private void installConfig(PluginInfo info, Path tmpConfigDir, Path destConfigDir) throws Exception {
    if (Files.isDirectory(tmpConfigDir) == false) {
        throw new UserException(ExitCodes.IO_ERROR, "config in plugin " + info.getName() + " is not a directory");
    }

    Files.createDirectories(destConfigDir);
    setFileAttributes(destConfigDir, CONFIG_DIR_PERMS);
    final PosixFileAttributeView destConfigDirAttributesView =
        Files.getFileAttributeView(destConfigDir.getParent(), PosixFileAttributeView.class);
    final PosixFileAttributes destConfigDirAttributes =
        destConfigDirAttributesView != null ? destConfigDirAttributesView.readAttributes() : null;
    if (destConfigDirAttributes != null) {
        setOwnerGroup(destConfigDir, destConfigDirAttributes);
    }

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(tmpConfigDir)) {
        for (Path srcFile : stream) {
            if (Files.isDirectory(srcFile)) {
                throw new UserException(ExitCodes.DATA_ERROR, "Directories not allowed in config dir for plugin " + info.getName());
            }

            Path destFile = destConfigDir.resolve(tmpConfigDir.relativize(srcFile));
            if (Files.exists(destFile) == false) {
                Files.copy(srcFile, destFile);
                setFileAttributes(destFile, CONFIG_FILES_PERMS);
                if (destConfigDirAttributes != null) {
                    setOwnerGroup(destFile, destConfigDirAttributes);
                }
            }
        }
    }
    IOUtils.rm(tmpConfigDir); // clean up what we just copied
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:38,代碼來源:InstallPluginCommand.java


注:本文中的java.nio.file.attribute.PosixFileAttributes類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。