下面列出了怎么用java.nio.file.attribute.BasicFileAttributes的API类实例代码及写法,或者点击链接到github查看源代码。
public static void cleanFiles() {
Path directory = Paths.get("target/test-files/");
try {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} catch (Exception ignore) {
}
}
private void registerAll(final Path start) {
// register directory and sub-directories
try {
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
if (ignorePaths.contains(dir)) {
return FileVisitResult.SKIP_SUBTREE;
} else {
register(dir);
return FileVisitResult.CONTINUE;
}
}
});
} catch (IOException e) {
// ignore to keep sample readable
}
}
@Override
public void close() throws Exception {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* This method is primarily used to give visual confirmation that a test case
* generated files when the compilation succeeds and so generates no other output,
* such as error messages.
*/
List<Path> showFiles(Path dir) throws IOException {
List<Path> files = new ArrayList<>();
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (Files.isRegularFile(file)) {
out.println("Found " + file);
files.add(file);
}
return FileVisitResult.CONTINUE;
}
});
return files;
}
public static void parseZip(String zipFile){
LOGGER.info("开始解析ZIP文件:"+zipFile);
try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) {
for(Path path : fs.getRootDirectories()){
LOGGER.info("处理目录:"+path);
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
LOGGER.info("处理文件:"+file);
// 拷贝到本地文件系统
Path temp = Paths.get("target/origin-html-temp.txt");
Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
parseFile(temp.toFile().getAbsolutePath());
return FileVisitResult.CONTINUE;
}
});
}
}catch (Exception e){
LOGGER.error("解析文本出错", e);
}
}
public static void main(String[] args) {
Path path = Paths.get("resources/lorem-ipsum.txt");
BasicFileAttributes attr;
try {
attr = Files.readAttributes(path, BasicFileAttributes.class);
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());
System.out.printf(outFormat, "size", attr.size());
System.out.printf("%n### bulk access to file attributes%n");
Map<String, Object> attrBulk;
attrBulk = Files.readAttributes(path, "basic:*", NOFOLLOW_LINKS);
for (String key : attrBulk.keySet()) {
System.out.printf("%s:%-16s: %s%n", "basic", key, attrBulk.get(key));
}
} catch (IOException ex) {
System.err.println("failed to obtain BasicFileAttributes " + ex.getMessage());
}
}
/**
* Delete fully the given path.
*
* (1) If it is a file, the file will be deleted.
*
* (2) If it is a directory, the directory and all its contents will be recursively deleted.
* If an exception is thrown, the directory may possibly be partially deleted.*
*
* (3) If it is a symlink, the symlink will be deleted but the symlink target will not be deleted.
*/
static void deleteFully(Path p) throws IOException {
if (!Files.exists(p, LinkOption.NOFOLLOW_LINKS)) {
LOG.trace("deleteFully: {} does not exist.", p);
return;
}
Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (e != null) {
// directory iteration failed
throw e;
}
delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
private void writePathInfo(Path path, BasicFileAttributes attrs) throws IOException {
MCRPath mcrPath = MCRPath.toMCRPath(path);
MCRPath relativePath = mcrPath.getRoot().relativize(mcrPath);
boolean isRoot = mcrPath.getNameCount() == 0;
jw.name("type").value(attrs.isDirectory() ? "directory" : "file");
if (isRoot) {
jw.name("mycoreobject").value(objId);
jw.name("mycorederivate").value(mcrPath.getOwner());
}
jw.name("name").value(isRoot ? "" : mcrPath.getFileName().toString());
jw.name("path")
.value(attrs.isDirectory() ? toStringValue(relativePath) : SEPARATOR_STRING + relativePath);
if (!isRoot) {
jw.name("parentPath").value(toStringValue(relativePath.getParent()));
}
addBasicAttributes(path, attrs);
}
@Test
public void testContainerVisitor() throws Exception {
File blobsPath = temporaryFolder.newFolder();
BlobContainer blobContainer = new BlobContainer(blobsPath.toPath());
blobContainer.getFile(digest("Content A")).createNewFile();
blobContainer.getFile(digest("Content B")).createNewFile();
blobContainer.getFile(digest("Content C")).createNewFile();
final AtomicInteger blobsCount = new AtomicInteger(0);
blobContainer.visitBlobs(new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
blobsCount.getAndIncrement();
return FileVisitResult.CONTINUE;
}
});
assertThat(blobsCount.get(), is(3));
}
public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException, SecurityException {
this.archivePath = archivePath;
if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) {
Map<String,String> env = Collections.singletonMap("multi-release", multiReleaseValue);
FileSystemProvider jarFSProvider = fsInfo.getJarFSProvider();
Assert.checkNonNull(jarFSProvider, "should have been caught before!");
this.fileSystem = jarFSProvider.newFileSystem(archivePath, env);
} else {
this.fileSystem = FileSystems.newFileSystem(archivePath, null);
}
packages = new HashMap<>();
for (Path root : fileSystem.getRootDirectories()) {
Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (isValid(dir.getFileName())) {
packages.put(new RelativeDirectory(root.relativize(dir).toString()), dir);
return FileVisitResult.CONTINUE;
} else {
return FileVisitResult.SKIP_SUBTREE;
}
}
});
}
}
/**
* A default, reusable and overridable means of adding file attributes to a document
*
* @param attributes The attributes of the scanned file as returned by
* {@link java.nio.file.Files#getFileAttributeView(Path, Class, LinkOption...)}
* @param doc The document representing the scanned file to which attributes should be added.
*/
default void addAttrs(BasicFileAttributes attributes, DocumentImpl doc) {
if (attributes != null) {
FileTime modifiedTime = attributes.lastModifiedTime();
FileTime accessTime = attributes.lastAccessTime();
FileTime creationTime = attributes.creationTime();
if (modifiedTime != null) {
doc.put("modified", String.valueOf(modifiedTime.toMillis()));
}
if (accessTime != null) {
doc.put("accessed", String.valueOf(accessTime.toMillis()));
}
if (creationTime != null) {
doc.put("created", String.valueOf(creationTime.toMillis()));
}
doc.put("file_size", String.valueOf(attributes.size()));
}
}
static void testNonEmptySystemExtDirs() throws Exception {
String home = System.getProperty("java.home");
Path ext = Paths.get(home, "lib", "ext");
String extDirs = System.getProperty("java.ext.dirs");
String[] dirs = extDirs.split(File.pathSeparator);
long count = 0;
for (String d : dirs) {
Path path = Paths.get(d);
if (Files.notExists(path) || path.equals(ext)) continue;
count += Files.find(path, 1, (Path p, BasicFileAttributes attr)
-> p.getFileName().toString().endsWith(".jar"))
.count();
}
if (count > 0) {
fatalError("-XX:+CheckEndorsedAndExtDirs");
}
}
@After
public void tearDown() throws Exception
{
Files.walkFileTree(_tmpDir,
new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
throws IOException
{
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
throws IOException
{
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* 获取文件创建时间
*
* @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();
}
/**
* 获取文件创建时间
*
* @param srcPath 文件绝对路径
* @return 时间
*/
public static Date getCreateTime(String srcPath) {
Path path = Paths.get(srcPath);
BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class,
LinkOption.NOFOLLOW_LINKS);
BasicFileAttributes attr;
try {
attr = basicview.readAttributes();
Date createDate = new Date(attr.creationTime().toMillis());
return createDate;
} catch (Exception e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.set(1970, 0, 1, 0, 0, 0);
return cal.getTime();
}
public Set<String> getDirNames() throws IOException {
ImmutableSet.Builder<String> contents = ImmutableSet.builder();
Files.walkFileTree(
root,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
// Skip leading and trailing slashes. Java 8 returns trailing slashes, whereas Java 11
// does not. Both return leading slashes.
String dirName = dir.toString().substring(1);
dirName = dirName.endsWith("/") ? dirName.substring(0, dirName.length() - 1) : dirName;
contents.add(dirName);
return FileVisitResult.CONTINUE;
}
});
return contents.build();
}
/**
* Starts searching for files in the given path, up to the specified depth.
*
* @param _p the FS path to search in
* @param _depth the depth of nested directories to search in
* @return a set of paths for all files found
*/
public Set<Path> search(@NotNull Path _p, int _depth) {
try {
if(Files.isDirectory(_p))
Files.walkFileTree(_p, new HashSet<FileVisitOption>(), _depth, this);
else if(Files.isRegularFile(_p))
this.visitFile(_p, Files.readAttributes(_p, BasicFileAttributes.class));
} catch (Exception e) {
AbstractFileSearch.getLog().error("Error while analyzing path [" + _p + "]: " + e.getMessage());
}
if(_p.isAbsolute())
AbstractFileSearch.getLog().info("Found [" + this.files.size() + "] files in absolute path [" + _p.toAbsolutePath() + "]");
else
AbstractFileSearch.getLog().info("Found [" + this.files.size() + "] files in relative path [" + _p + "], i.e., absolute path [" + _p.toAbsolutePath() + "]");
return this.files;
}
private static void printJavaLicenseFiles(OutErr outErr, Path bundledJdkOrJre) {
try {
Files.walkFileTree(
bundledJdkOrJre,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
throws IOException {
if (JAVA_LICENSE_FILES.contains(path.getFileName().toString())) {
outErr.printOutLn(path + ":\n");
Files.copy(path, outErr.getOutputStream());
outErr.printOutLn("\n");
}
return super.visitFile(path, basicFileAttributes);
}
});
} catch (IOException e) {
throw new UncheckedIOException(
"I/O error while trying to print license file of bundled JDK or JRE: " + e.getMessage(),
e);
}
}
/** Recursively delete a directory. */
private static void deleteTree(final Path directory) throws IOException {
if (directory.toFile().exists()) {
Files.walkFileTree(
directory,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Objects.nonNull(file);
Objects.nonNull(attrs);
Path found = file.getFileName();
for (String name : matchers.keySet())
if (!results.containsKey(name)) {
PathMatcher matcher = matchers.get(name);
if (null != found && matcher.matches(found) && Files.isExecutable(file) && check(file, name, version)) {
results.put(name, file);
if (results.size() == matchers.size())
return FileVisitResult.TERMINATE;
}
}
return FileVisitResult.CONTINUE;
}
public static List<MCRValidationResult> validateZipFile(final MCRFileValidator validator, Path zipFile)
throws IOException, URISyntaxException {
try (FileSystem zipfs = FileSystems.newFileSystem(new URI("jar:" + zipFile.toUri()), new HashMap<>())) {
final Path sourcePath = zipfs.getPath("/");
ArrayList<MCRValidationResult> validationResults = new ArrayList<>();
Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
MCRValidationResult validationResult = validator.validate(file);
if (!validationResult.isValid()) {
validationResults.add(validationResult);
}
return FileVisitResult.CONTINUE;
}
});
return validationResults;
}
}
public static Set<String> parseZip(String zipFile){
Set<String> data = new HashSet<>();
LOGGER.info("开始解析ZIP文件:"+zipFile);
try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), PhraseExtractor.class.getClassLoader())) {
for(Path path : fs.getRootDirectories()){
LOGGER.info("处理目录:"+path);
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
LOGGER.info("处理文件:"+file);
// 拷贝到本地文件系统
Path temp = Paths.get("target/origin-html-temp.txt");
Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
data.addAll(parseFile(temp.toFile().getAbsolutePath()));
return FileVisitResult.CONTINUE;
}
});
}
}catch (Exception e){
LOGGER.error("解析文本出错", e);
}
return data;
}
private void handlePathEvent(MCREvent evt, Path file, BasicFileAttributes attrs) {
if (!(file instanceof MCRPath)) {
return;
}
MCRPath path = MCRPath.toMCRPath(file);
MCRContent xml;
try {
xml = new MCRJDOMContent(MCRPathXML.getFileXML(path, attrs));
handleEvent(evt, xml, path.toString());
} catch (IOException e) {
LOGGER.error("Error while generating mail for {}", file, e);
}
}
@Test
public void canReadAttributes() throws IOException {
tmp.newFolder("dir1");
tmp.newFile("dir1/file1");
BasicFileAttributes attributes =
filesystemView.readAttributes(Paths.get("dir1/file1"), BasicFileAttributes.class);
assertTrue(attributes.isRegularFile());
assertFalse(attributes.isDirectory());
attributes = filesystemView.readAttributes(Paths.get("dir1"), BasicFileAttributes.class);
assertFalse(attributes.isRegularFile());
assertTrue(attributes.isDirectory());
}
/**
* Returns the attributes of the given file, taking into account whether
* the walk is following sym links is not. The {@code canUseCached}
* argument determines whether this method can use cached attributes.
*/
private BasicFileAttributes getAttributes(Path file, boolean canUseCached)
throws IOException
{
// if attributes are cached then use them if possible
if (canUseCached &&
(file instanceof BasicFileAttributesHolder) &&
(System.getSecurityManager() == null))
{
BasicFileAttributes cached = ((BasicFileAttributesHolder)file).get();
if (cached != null && (!followLinks || !cached.isSymbolicLink())) {
return cached;
}
}
// attempt to get attributes of file. If fails and we are following
// links then a link target might not exist so get attributes of link
BasicFileAttributes attrs;
try {
attrs = Files.readAttributes(file, BasicFileAttributes.class, linkOptions);
} catch (IOException ioe) {
if (!followLinks)
throw ioe;
// attempt to get attrmptes without following links
attrs = Files.readAttributes(file,
BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
}
return attrs;
}
private static void deleteGeneratedFiles() {
Path p = Paths.get("generated");
if (Files.exists(p)) {
try {
Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException exc) throws IOException {
if (exc == null) {
Files.delete(dir);
return CONTINUE;
} else {
throw exc;
}
}
});
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
@Nullable
private static String generateFileDoc(@Nonnull PsiFile psiFile, boolean withUrl) {
VirtualFile file = PsiUtilCore.getVirtualFile(psiFile);
File ioFile = file == null || !file.isInLocalFileSystem() ? null : VfsUtilCore.virtualToIoFile(file);
BasicFileAttributes attr = null;
try {
attr = ioFile == null ? null : Files.readAttributes(Paths.get(ioFile.toURI()), BasicFileAttributes.class);
}
catch (Exception ignored) {
}
if (attr == null) return null;
FileType type = file.getFileType();
String typeName = type == UnknownFileType.INSTANCE ? "Unknown" : type == PlainTextFileType.INSTANCE ? "Text" : type instanceof ArchiveFileType ? "Archive" : type.getId();
String languageName = type.isBinary() ? "" : psiFile.getLanguage().getDisplayName();
return (withUrl ? DocumentationMarkup.DEFINITION_START + file.getPresentableUrl() + DocumentationMarkup.DEFINITION_END + DocumentationMarkup.CONTENT_START : "") +
getVcsStatus(psiFile.getProject(), file) +
getScope(psiFile.getProject(), file) +
"<p><span class='grayed'>Size:</span> " +
StringUtil.formatFileSize(attr.size()) +
"<p><span class='grayed'>Type:</span> " +
typeName +
(type.isBinary() || typeName.equals(languageName) ? "" : " (" + languageName + ")") +
"<p><span class='grayed'>Modified:</span> " +
DateFormatUtil.formatDateTime(attr.lastModifiedTime().toMillis()) +
"<p><span class='grayed'>Created:</span> " +
DateFormatUtil.formatDateTime(attr.creationTime().toMillis()) +
(withUrl ? DocumentationMarkup.CONTENT_END : "");
}
private ImmutableSortedSet<Path> findFiles(Path root, PathMatcher matcher) throws IOException {
ImmutableSortedSet.Builder<Path> files = ImmutableSortedSet.naturalOrder();
Files.walkFileTree(
root,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (matcher.matches(file)) {
files.add(file);
}
return FileVisitResult.CONTINUE;
}
});
return files.build();
}
/** {@inheritDoc} */
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path fileName = file.getFileName();
if (fileName != null && matcher.matches(fileName)) {
firstMatchedFile = file;
return TERMINATE;
}
return CONTINUE;
}
@Test
public void getSizeAttributeOfDirectory_shouldReturnZero() throws IOException {
writeToCache("/dir/file.txt");
commitToMaster();
initGitFileSystem();
BasicFileAttributes attributes = readPosixAttributes("/dir");
assertEquals(0L, attributes.size());
}