类java.nio.file.LinkOption源码实例Demo

下面列出了怎么用java.nio.file.LinkOption的API类实例代码及写法,或者点击链接到github查看源代码。

public void addFileInfos(Map<String, Path> paths) {
    if (paths != null && !paths.isEmpty()) {
        List<Object> infos = new ArrayList<>();
        for(Entry<String, Path> path: paths.entrySet()) {

            try {
                if(Files.isReadable(path.getValue())) {
                    final String chcksm = DigestUtils.sha256Hex(Files.readAllBytes(path.getValue()));
                    FileTime lm = Files.getLastModifiedTime(path.getValue(), LinkOption.NOFOLLOW_LINKS);
                    Map<String, Object> innerInfos = new HashMap<>();
                    innerInfos.put("sha256", chcksm);
                    innerInfos.put("last_modified", formatTime(lm.toMillis()));
                    innerInfos.put("key", path.getKey());
                    innerInfos.put("path", path.getValue().toAbsolutePath().toString());
                    infos.add(innerInfos);
                }
            } catch (Throwable e) {
                //ignore non readable files
            }
        }
        auditInfo.put(COMPLIANCE_FILE_INFOS, infos);
    }
}
 
源代码2 项目: Java-Coding-Problems   文件: Main.java
public static void main(String[] args) throws IOException {

        Path path = Paths.get("/learning/packt", "JavaModernChallenge.pdf");

        String pathToString = path.toString();
        System.out.println("Path to String: " + pathToString);

        URI pathToURI = path.toUri();
        System.out.println("Path to URI: " + pathToURI);

        Path pathToAbsolutePath = path.toAbsolutePath();
        System.out.println("Path to absolute path: " + pathToAbsolutePath);

        Path path2 = Paths.get("/learning/books/../PACKT/./", "JavaModernChallenge.pdf");
        Path realPath = path2.toRealPath(LinkOption.NOFOLLOW_LINKS);
        System.out.println("Path to 'real' path: " + realPath);

        File pathToFile = path.toFile();
        Path fileToPath = pathToFile.toPath();
        System.out.println("Path to file name: " + pathToFile.getName());
        System.out.println("File to path: " + fileToPath);
    }
 
源代码3 项目: stone   文件: HaloUtils.java
/**
 * 获取文件创建时间
 *
 * @param srcPath 文件绝对路径
 *
 * @return 时间
 */
public static Date getCreateTime(String srcPath) {
    final Path path = Paths.get(srcPath);
    final BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
    BasicFileAttributes attr;
    try {
        attr = basicview.readAttributes();
        final Date createDate = new Date(attr.creationTime().toMillis());
        return createDate;
    } catch (Exception e) {
        e.printStackTrace();
    }
    final Calendar cal = Calendar.getInstance();
    cal.set(1970, 0, 1, 0, 0, 0);
    return cal.getTime();
}
 
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path,
		Class<V> type, LinkOption... options) {
	BundleFileSystem fs = (BundleFileSystem) path.getFileSystem();
	if (path.toAbsolutePath().equals(fs.getRootDirectory())) {
		// Bug in ZipFS, it will fall over as there is no entry for /
		//
		// Instead we'll just give a view of the source (e.g. the zipfile
		// itself).
		// Modifying its times is a bit futile since they are likely to be
		// overriden when closing, but this avoids a NullPointerException
		// in Files.setTimes().
		return Files.getFileAttributeView(fs.getSource(), type, options);
	}
	return origProvider(path).getFileAttributeView(fs.unwrap(path), type,
			options);
}
 
源代码5 项目: mirror   文件: WatchmanFileWatcher.java
private void readSymlinkTarget(Update.Builder ub) {
  try {
    Path path = ourRoot.resolve(ub.getPath());
    Path symlink = Files.readSymbolicLink(path);
    String targetPath;
    if (symlink.isAbsolute()) {
      targetPath = path.getParent().normalize().relativize(symlink.normalize()).toString();
    } else {
      // the symlink is already relative, so we can leave it alone, e.g. foo.txt
      targetPath = symlink.toString();
    }
    ub.setSymlink(targetPath);
    // Ensure our modtime is of the symlink itself (I'm not actually
    // sure which modtime watchman sends back, but this is safest).
    ub.setModTime(Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS).toMillis());
  } catch (IOException e) {
    // ignore as the file probably disappeared
    log.debug("Exception reading symlink, assumed stale", e);
  }
}
 
private static void checkPath(String keystoreFilePath, String fileNameLogOnly) {

        if (keystoreFilePath == null || keystoreFilePath.length() == 0) {
            throw new ElasticsearchException("Empty file path for " + fileNameLogOnly);
        }

        if (Files.isDirectory(Paths.get(keystoreFilePath), LinkOption.NOFOLLOW_LINKS)) {
            throw new ElasticsearchException(
                    "Is a directory: " + keystoreFilePath + " Expected a file for " + fileNameLogOnly);
        }

        if (!Files.isReadable(Paths.get(keystoreFilePath))) {
            throw new ElasticsearchException("Unable to read " + keystoreFilePath + " (" + Paths.get(keystoreFilePath)
                    + "). Please make sure this files exists and is readable regarding to permissions. Property: "
                    + fileNameLogOnly);
        }
    }
 
源代码7 项目: zip4j   文件: FileUtilsTestWindows.java
private DosFileAttributeView mockDosFileAttributeView(Path path, boolean fileExists, DosFileAttributes dosFileAttributes) throws IOException {
  FileSystemProvider fileSystemProvider = mock(FileSystemProvider.class);
  FileSystem fileSystem = mock(FileSystem.class);
  DosFileAttributeView dosFileAttributeView = mock(DosFileAttributeView.class);

  when(fileSystemProvider.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS)).thenReturn(dosFileAttributes);
  when(path.getFileSystem()).thenReturn(fileSystem);
  when(fileSystemProvider.getFileAttributeView(path, DosFileAttributeView.class, LinkOption.NOFOLLOW_LINKS))
      .thenReturn(dosFileAttributeView);
  when(path.getFileSystem().provider()).thenReturn(fileSystemProvider);

  if (!fileExists) {
    doThrow(new IOException()).when(fileSystemProvider).checkAccess(path);
  }

  return dosFileAttributeView;
}
 
源代码8 项目: sftp-fs   文件: SFTPFileSystemTest.java
@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());
}
 
源代码9 项目: openjdk-jdk9   文件: PollingWatchService.java
PollingWatchKey(Path dir, PollingWatchService watcher, Object fileKey)
    throws IOException
{
    super(dir, watcher);
    this.fileKey = fileKey;
    this.valid = true;
    this.tickCount = 0;
    this.entries = new HashMap<Path,CacheEntry>();

    // get the initial entries in the directory
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path entry: stream) {
            // don't follow links
            long lastModified =
                Files.getLastModifiedTime(entry, LinkOption.NOFOLLOW_LINKS).toMillis();
            entries.put(entry.getFileName(), new CacheEntry(lastModified, tickCount));
        }
    } catch (DirectoryIteratorException e) {
        throw e.getCause();
    }
}
 
源代码10 项目: sftp-fs   文件: SFTPFileSystemTest.java
@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());
}
 
源代码11 项目: meghanada-server   文件: FileUtils.java
@SuppressWarnings("try")
public static Optional<File> getClassFile(
    String path, final Set<File> sourceRoots, final File out) throws IOException {

  try (TelemetryUtils.ScopedSpan scope =
      TelemetryUtils.startScopedSpan("FileUtils.getClassFile")) {
    TelemetryUtils.ScopedSpan.addAnnotation(
        TelemetryUtils.annotationBuilder()
            .put("sourceRoot", sourceRoots.toString())
            .put("out", out.getPath())
            .build("args"));
    String outPath = out.getCanonicalPath();
    for (File rootFile : sourceRoots) {
      final String root = rootFile.getCanonicalPath();
      if (path.startsWith(root)) {
        final String src = path.substring(root.length());
        final String classFile = StringUtils.replace(src, JAVA_EXT, CLASS_EXT);
        final Path p = Paths.get(outPath, classFile);
        if (Files.exists(p, LinkOption.NOFOLLOW_LINKS)) {
          return Optional.of(p.toFile());
        }
      }
    }
    return Optional.empty();
  }
}
 
源代码12 项目: p4ic4idea   文件: SymbolicLinkHelper.java
/**
 * Gets the last modified time for a symbolic link.
 *
 * Note: symbolic links are not followed (NOFOLLOW_LINKS LinkOption)
 *
 * @param link the path to the symbolic link
 * @return last modified time of the symbolic link
 */
public static long getLastModifiedTime(String link) {
  if (nonNull(link)) {
    try {
      Path linkPath = Paths.get(link);
      if (nonNull(linkPath)) {
        FileTime fileTimeObject = Files.getLastModifiedTime(linkPath, LinkOption.NOFOLLOW_LINKS);
        if (nonNull(fileTimeObject)) {
          return fileTimeObject.toMillis();
        }
      }
    } catch (Throwable thr) {
      Log.error("Unexpected exception invoking method: %s", thr.getLocalizedMessage());
      Log.exception(thr);
    }
  }
  return 0L;
}
 
源代码13 项目: meghanada-server   文件: FileUtils.java
@SuppressWarnings("try")
private static boolean hasClassFile(
    final String path, final Set<File> sourceRoots, final File out) throws IOException {

  try (TelemetryUtils.ScopedSpan scope =
      TelemetryUtils.startScopedSpan("FileUtils.hasClassFile")) {
    TelemetryUtils.ScopedSpan.addAnnotation(
        TelemetryUtils.annotationBuilder()
            .put("sourceRoot", sourceRoots.toString())
            .put("out", out.getPath())
            .build("args"));
    final String outPath = out.getCanonicalPath();
    for (final File rootFile : sourceRoots) {
      final String root = rootFile.getCanonicalPath();
      if (path.startsWith(root)) {
        final String src = path.substring(root.length());
        final String classFile = StringUtils.replace(src, JAVA_EXT, CLASS_EXT);
        final Path p = Paths.get(outPath, classFile);
        return Files.exists(p, LinkOption.NOFOLLOW_LINKS);
      }
    }
    return false;
  }
}
 
源代码14 项目: baratine   文件: FileProviderClasspath.java
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path,
                                                        Class<A> type,
                                                        LinkOption... options)
                                                            throws IOException
{
  URL url = getURL(path);
  
  if (url == null) {
    throw new FileNotFoundException(L.l("{0} does not exist", path));
  }
  
  if (! type.equals(BasicFileAttributes.class)) {
    throw new UnsupportedOperationException(type.getName());
  }
  
  PathBase pathBase = (PathBase) path;
  
  return (A) new BasicFileAttributesImpl(pathBase.path(), url);
}
 
源代码15 项目: netbeans   文件: PasswordFile.java
/**
 * Create password file to be written with access permissions to read
 * and write by user only.
 * <p/>
 * @return Value of <code>true</code> if new file was created
 *         or <code>false</code> otherwise
 */
private boolean createFilePosix() {
    final String METHOD = "createFilePosix";
    boolean success = false;
    try {
        if (Files.notExists(file, new LinkOption[0])) {
            Files.createFile(file, PosixFilePermissions
                    .asFileAttribute(CREATE_FILE_PERMISSIONS));
            success = true;
        } else {
            Files.setPosixFilePermissions(file, CREATE_FILE_PERMISSIONS);
            LOGGER.log(Level.INFO, METHOD, "exists", file.toString());
        }
    } catch (UnsupportedOperationException uoe) {
        LOGGER.log(Level.INFO, METHOD, "unsupported", file.toString());
    } catch (FileAlreadyExistsException faee) {
        LOGGER.log(Level.INFO, METHOD, "exists", file.toString());
    } catch (IOException ioe) {
        LOGGER.log(Level.INFO, METHOD, "ioException", ioe);
    }
    return success;
}
 
源代码16 项目: scava   文件: MigrationService.java
private String getM3model(MavenLibrary lib) throws Exception {
	// TODO CHECK HERE
	Artifact v1 = downloader.downloadArtifactTo(
			new DefaultArtifact(
					String.format("%s:%s:%s", lib.getGroupid(), lib.getArtifactid(), lib.getVersion())),
			mavenRepoPath);
	lib.setArtifact(v1);
	String libM3 = lib.getArtifact().getFile().getAbsolutePath() + ".m3";
	if (!Files.exists(Paths.get(libM3), new LinkOption[] { LinkOption.NOFOLLOW_LINKS })) {
		String libJar = lib.getArtifact().getFile().getAbsolutePath();
		boolean bLib1 = maracas.storeM3(libJar, libM3);
		logger.info("Lib1 store: " + bLib1);
		if (!bLib1) {
			logger.error("error computing {} m3 model", lib.getCoordinate());
			throw new Exception();
		}
	}
	return libM3;
}
 
源代码17 项目: openjdk-8-source   文件: PathFileObject.java
@Override
public boolean isNameCompatible(String simpleName, Kind kind) {
    simpleName.getClass();
    // null check
    if (kind == Kind.OTHER && getKind() != kind) {
        return false;
    }
    String sn = simpleName + kind.extension;
    String pn = path.getFileName().toString();
    if (pn.equals(sn)) {
        return true;
    }
    if (pn.equalsIgnoreCase(sn)) {
        try {
            // allow for Windows
            return path.toRealPath(LinkOption.NOFOLLOW_LINKS).getFileName().toString().equals(sn);
        } catch (IOException e) {
        }
    }
    return false;
}
 
源代码18 项目: p4ic4idea   文件: SymbolicLinkHelper.java
/**
 * Gets the last modified time for a symbolic link.
 *
 * Note: symbolic links are not followed (NOFOLLOW_LINKS LinkOption)
 *
 * @param link the path to the symbolic link
 * @return last modified time of the symbolic link
 */
public static long getLastModifiedTime(String link) {
  if (nonNull(link)) {
    try {
      Path linkPath = Paths.get(link);
      if (nonNull(linkPath)) {
        FileTime fileTimeObject = Files.getLastModifiedTime(linkPath, LinkOption.NOFOLLOW_LINKS);
        if (nonNull(fileTimeObject)) {
          return fileTimeObject.toMillis();
        }
      }
    // p4ic4idea: Do not catch throwable unless you're really careful
    //} catch (Throwable thr) {
    } catch (Exception thr) {
      Log.error("Unexpected exception invoking method: %s", thr.getLocalizedMessage());
      Log.exception(thr);
    }
  }
  return 0L;
}
 
源代码19 项目: SonarPet   文件: RecursiveDeleteOnExitHook.java
@Override
public void run() {
    // NOTE: Iterate backwards so last added is first deleted
    // For some reason this is important (see JDK DeleteOnExitHook(
    for (int i = toDelete.size() - 1; i >= 0; i--) {
        Path target = toDelete.get(i);
        try {
            if (Files.isDirectory(target, LinkOption.NOFOLLOW_LINKS)) {
                Files.walkFileTree(target, new RecursiveDirectoryDeleter());
            } else {
                Files.deleteIfExists(target);
            }
        } catch (IOException e) {
            //noinspection UseOfSystemOutOrSystemErr - VM is shutting down
            System.err.println("Unable to delete " + toDelete + ": " + e);
        }
    }
}
 
源代码20 项目: mycore   文件: MCRDirectoryStream.java
@Override
public SecureDirectoryStream<Path> newDirectoryStream(Path path, LinkOption... options) throws IOException {
    checkClosed();
    MCRPath mcrPath = checkFileSystem(path);
    if (mcrPath.isAbsolute()) {
        return (SecureDirectoryStream<Path>) Files.newDirectoryStream(mcrPath);
    }
    MCRFilesystemNode childByPath = dir.getChildByPath(mcrPath.toString());
    if (childByPath == null || childByPath instanceof MCRFile) {
        throw new NoSuchFileException(dir.toString(), path.toString(), "Does not exist or is a file.");
    }
    return new MCRDirectoryStream((MCRDirectory) childByPath, MCRPath.toMCRPath(path.resolve(mcrPath)));
}
 
源代码21 项目: openjdk-8   文件: FaultyFileSystem.java
@Override
public void setAttribute(Path file, String attribute, Object value, LinkOption... options)
    throws IOException
{
    triggerEx(file, "setAttribute");
    Files.setAttribute(unwrap(file), attribute, value, options);
}
 
源代码22 项目: SubServers-2   文件: SubCreatorImpl.java
private void updateDirectory(File from, File to) {
    if (from.isDirectory() && !Files.isSymbolicLink(from.toPath())) {
        if (!to.exists()) {
            to.mkdirs();
        }

        String files[] = from.list();

        for (String file : files) {
            File srcFile = new File(from, file);
            File destFile = new File(to, file);

            updateDirectory(srcFile, destFile);
        }
    } else {
        try {
            if (!to.exists() || from.length() != to.length() || !Arrays.equals(generateSHA256(to), generateSHA256(from))) {
                if (to.exists()) {
                    if (to.isDirectory()) Util.deleteDirectory(to);
                    else to.delete();
                }
                Files.copy(from.toPath(), to.toPath(), LinkOption.NOFOLLOW_LINKS, StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
源代码23 项目: Bytecoder   文件: JrtFileSystem.java
JrtFileAttributes getFileAttributes(JrtPath path, LinkOption... options)
        throws IOException {
    Node node = checkNode(path);
    if (node.isLink() && followLinks(options)) {
        return new JrtFileAttributes(node.resolveLink(true));
    }
    return new JrtFileAttributes(node);
}
 
源代码24 项目: jdk8u-jdk   文件: FaultyFileSystem.java
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path file,
                                                            Class<V> type,
                                                            LinkOption... options)
{
    return Files.getFileAttributeView(unwrap(file), type, options);
}
 
源代码25 项目: zip4j   文件: FileUtils.java
private static String getNameOfFileInZip(File fileToAdd, String fileNameInZip) throws IOException {
  if (isStringNotNullAndNotEmpty(fileNameInZip)) {
    return fileNameInZip;
  }

  if (isSymbolicLink(fileToAdd)) {
    return fileToAdd.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS).getFileName().toString();
  }

  return fileToAdd.getName();
}
 
源代码26 项目: jdk8u-jdk   文件: FaultyFileSystem.java
@Override
public Map<String,Object> readAttributes(Path file, String attributes, LinkOption... options)
    throws IOException
{
    triggerEx(file, "readAttributes");
    return Files.readAttributes(unwrap(file), attributes, options);
}
 
源代码27 项目: sftp-fs   文件: SFTPFileSystemProvider.java
/**
 * Reads a file's attributes as a bulk operation.
 * This method works in exactly the manner specified by the {@link Files#readAttributes(Path, Class, LinkOption...)} method.
 * <p>
 * This provider supports {@link BasicFileAttributes} and {@link PosixFileAttributes} (there is no {@code FileOwnerFileAttributes}).
 * All other classes will result in an {@link UnsupportedOperationException} to be thrown.
 */
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException {
    if (type == BasicFileAttributes.class || type == PosixFileAttributes.class) {
        return type.cast(toSFTPPath(path).readAttributes(options));
    }
    throw Messages.fileSystemProvider().unsupportedFileAttributesType(type);
}
 
源代码28 项目: sftp-fs   文件: SFTPFileSystem.java
PosixFileAttributes readAttributes(SFTPPath path, LinkOption... options) throws IOException {
    boolean followLinks = LinkOptionSupport.followLinks(options);
    try (Channel channel = channelPool.get()) {
        SftpATTRS attributes = getAttributes(channel, path, followLinks);
        return new SFTPPathFileAttributes(attributes);
    }
}
 
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path,
		Class<A> type, LinkOption... options) throws IOException {
	BundleFileSystem fs = (BundleFileSystem) path.getFileSystem();
	return origProvider(path)
			.readAttributes(fs.unwrap(path), type, options);
}
 
源代码30 项目: TencentKona-8   文件: FaultyFileSystem.java
@Override
public void setAttribute(Path file, String attribute, Object value, LinkOption... options)
    throws IOException
{
    triggerEx(file, "setAttribute");
    Files.setAttribute(unwrap(file), attribute, value, options);
}
 
 类所在包
 类方法
 同包方法