下面列出了怎么用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);
}
}
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);
}
/**
* 获取文件创建时间
*
* @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);
}
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);
}
}
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;
}
@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());
}
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();
}
}
@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());
}
@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();
}
}
/**
* 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;
}
@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;
}
}
@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);
}
/**
* 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;
}
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;
}
@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;
}
/**
* 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;
}
@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);
}
}
}
@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)));
}
@Override
public void setAttribute(Path file, String attribute, Object value, LinkOption... options)
throws IOException
{
triggerEx(file, "setAttribute");
Files.setAttribute(unwrap(file), attribute, value, options);
}
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();
}
}
}
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);
}
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path file,
Class<V> type,
LinkOption... options)
{
return Files.getFileAttributeView(unwrap(file), type, options);
}
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();
}
@Override
public Map<String,Object> readAttributes(Path file, String attributes, LinkOption... options)
throws IOException
{
triggerEx(file, "readAttributes");
return Files.readAttributes(unwrap(file), attributes, options);
}
/**
* 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);
}
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);
}
@Override
public void setAttribute(Path file, String attribute, Object value, LinkOption... options)
throws IOException
{
triggerEx(file, "setAttribute");
Files.setAttribute(unwrap(file), attribute, value, options);
}