`

java 7 NIO2(2) Metadata File Attributes

    博客分类:
  • java
 
阅读更多

java 7 NIO2新特性支持操作文件的属性,使用NIO2的API操作你自己的文件元数据。

NIO2的属性操作相关类包

 

我们看下示例代码:

package com.mime;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.AclEntry;
import java.nio.file.attribute.AclEntryPermission;
import java.nio.file.attribute.AclEntryType;
import java.nio.file.attribute.AclFileAttributeView;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.nio.file.attribute.FileStoreAttributeView;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.GroupPrincipal;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.util.List;
import java.util.Set;

import static java.nio.file.LinkOption.NOFOLLOW_LINKS;

public class NIO2FileAttribute {

	public static void main(String[] args) {
		FileSystem fs = FileSystems.getDefault();
		Set<String> views = fs.supportedFileAttributeViews();
		for (String view : views) {
			System.out.println(view);
		}
		/*
		 * BasicFileAttributeView: This is a view of basic attributes that must
		 * be supported by all file system implementations. The attribute view
		 * name is basic. • DosFileAttributeView: This view provides the
		 * standard four supported attributes on file systems that support the
		 * DOS attributes. The attribute view name is dos. •
		 * PosixFileAttributeView: This view extends the basic attribute view
		 * with attributes supported on file systems that support the POSIX
		 * (Portable Operating System Interface for Unix) family of standards,
		 * such as Unix. The attribute view name is posix. •
		 * FileOwnerAttributeView: This view is supported by any file system
		 * implementation that supports the concept of a file owner. The
		 * attribute view name is owner. • AclFileAttributeView: This view
		 * supports reading or updating a file’s ACL. The NFSv4 ACL model is
		 * supported. The attribute view name is acl.
		 * UserDefinedFileAttributeView: This view enables support of metadata
		 * that is user defined.
		 */

		for (FileStore store : fs.getFileStores()) {
			boolean supported = store
					.supportsFileAttributeView(BasicFileAttributeView.class);
			System.out.println(store.name() + " ---" + supported);
		}
		Path path = null;
		try {
			path = Paths.get(System.getProperty("user.home"), "www",
					"pyweb.settings");
			FileStore store = Files.getFileStore(path);
			boolean supported = store.supportsFileAttributeView("basic");
			System.out.println(store.name() + " ---" + supported);
		} catch (IOException e) {
			System.err.println(e);
		}

		BasicFileAttributes attr = null;
		try {
			attr = Files.readAttributes(path, BasicFileAttributes.class);
		} catch (IOException e) {
			System.err.println(e);
		}
		System.out.println("File size: " + attr.size());
		System.out.println("File creation time: " + attr.creationTime());
		System.out.println("File was last accessed at: "
				+ attr.lastAccessTime());
		System.out.println("File was last modified at: "
				+ attr.lastModifiedTime());
		System.out.println("Is directory? " + attr.isDirectory());
		System.out.println("Is  regular file? " + attr.isRegularFile());
		System.out.println("Is  symbolic link? " + attr.isSymbolicLink());
		System.out.println("Is  other? " + attr.isOther());

		// 只获取某个属性 [view-name:]attribute-name
		/**
		 * Basic attribute names are listed here: lastModifiedTime
		 * lastAccessTime creationTime size isRegularFile isDirectory
		 * isSymbolicLink isOther fileKey
		 **/
		try {
			long size = (Long) Files.getAttribute(path, "basic:size",
					java.nio.file.LinkOption.NOFOLLOW_LINKS);
			System.out.println("Size: " + size);
		} catch (IOException e) {
			System.err.println(e);
		}
		// Update a Basic Attribute
		long time = System.currentTimeMillis();
		FileTime fileTime = FileTime.fromMillis(time);
		try {
			Files.getFileAttributeView(path, BasicFileAttributeView.class)
					.setTimes(fileTime, fileTime, fileTime);
		} catch (IOException e) {
			System.err.println(e);
		}
		try {
			Files.setLastModifiedTime(path, fileTime);
		} catch (IOException e) {
			System.err.println(e);
		}

		try {
			Files.setAttribute(path, "basic:lastModifiedTime", fileTime,
					NOFOLLOW_LINKS);
			Files.setAttribute(path, "basic:creationTime", fileTime,
					NOFOLLOW_LINKS);
			Files.setAttribute(path, "basic:lastAccessTime", fileTime,
					NOFOLLOW_LINKS);
		} catch (IOException e) {
			System.err.println(e);
		}
		// DosFileAttributeView DOS attributes can be acquired with the
		// following names:hidden readonly system archive
		DosFileAttributes docattr = null;
		try {
			docattr = Files.readAttributes(path, DosFileAttributes.class);
		} catch (IOException e) {
			System.err.println(e);
		}
		System.out.println("Is read only ? " + docattr.isReadOnly());
		System.out.println("Is Hidden ? " + docattr.isHidden());
		System.out.println("Is archive ? " + docattr.isArchive());
		System.out.println("Is  system ? " + docattr.isSystem());

		// FileOwnerAttributeView
		// Set a File Owner Using Files.setOwner() 三种设置文件所有者的方法
		UserPrincipal owner = null;
		try {
			owner = path.getFileSystem().getUserPrincipalLookupService()
					.lookupPrincipalByName("apress");
			Files.setOwner(path, owner);
		} catch (IOException e) {
			System.err.println(e);
		}
		FileOwnerAttributeView foav = Files.getFileAttributeView(path,
				FileOwnerAttributeView.class);
		try {
			owner = path.getFileSystem().getUserPrincipalLookupService()
					.lookupPrincipalByName("apress");
			foav.setOwner(owner);
		} catch (IOException e) {
			System.err.println(e);
		}
		try {
			owner = path.getFileSystem().getUserPrincipalLookupService()
					.lookupPrincipalByName("apress");
			Files.setAttribute(path, "owner:owner", owner, NOFOLLOW_LINKS);
		} catch (IOException e) {
			System.err.println(e);
		}
		// 获取文件所有者
		try {
			String ownerName = foav.getOwner().getName();
			System.out.println(ownerName);
		} catch (IOException e) {
			System.err.println(e);
		}
		try {
			UserPrincipal owner1 = (UserPrincipal) Files.getAttribute(path,
					"owner:owner", NOFOLLOW_LINKS);
			System.out.println(owner1.getName());
		} catch (IOException e) {
			System.err.println(e);
		}

		// POSIX View file owner, group owner, and nine related access
		// permissions (read, write, members of the same group, etc.). •group
		// permissions

		PosixFileAttributes positattr = null;
		try {
			positattr = Files.readAttributes(path, PosixFileAttributes.class);
		} catch (IOException e) {
			System.err.println(e);
		}
		System.out.println("File owner: " + positattr.owner().getName());
		System.out.println("File group: " + positattr.group().getName());
		System.out.println("File permissions: "
				+ positattr.permissions().toString());

		// 设置文件访问权限
		FileAttribute<Set<PosixFilePermission>> posixattrs = PosixFilePermissions
				.asFileAttribute(positattr.permissions());
		try {
			Files.createFile(path, posixattrs);
		} catch (IOException e) {
			System.err.println(e);
		}
		Set<PosixFilePermission> permissions = PosixFilePermissions
				.fromString("rw-r--r--");
		try {
			Files.setPosixFilePermissions(path, permissions);
		} catch (IOException e) {
			System.err.println(e);
		}

		// 设置分组用户
		try {
			GroupPrincipal group = path.getFileSystem()
					.getUserPrincipalLookupService()
					.lookupPrincipalByGroupName("apressteam");
			Files.getFileAttributeView(path, PosixFileAttributeView.class)
					.setGroup(group);
		} catch (IOException e) {
			System.err.println(e);
		}

		// 查询组用户
		try {
			GroupPrincipal group = (GroupPrincipal) Files.getAttribute(path,
					"posix:group", NOFOLLOW_LINKS);
			System.out.println(group.getName());
		} catch (IOException e) {
			System.err.println(e);
		}

		// ACL View access control list acl owner
		// 查询acl属性
		List<AclEntry> acllist = null;
		AclFileAttributeView aclview = Files.getFileAttributeView(path,
				AclFileAttributeView.class);
		try {
			acllist = aclview.getAcl();
			for (AclEntry aclentry : acllist) {
				System.out
						.println("++++++++++++++++++++++++++++++++++++++++++++++++++++");
				System.out.println("Principal: "
						+ aclentry.principal().getName());
				System.out.println("Type: " + aclentry.type().toString());
				System.out.println("Permissions: "
						+ aclentry.permissions().toString());
				System.out.println("Flags: " + aclentry.flags().toString());
			}
		} catch (Exception e) {
			System.err.println(e);
		}

		// 设置ACL属性
		try {
			// Lookup for the principal
			UserPrincipal user = path.getFileSystem()
					.getUserPrincipalLookupService()
					.lookupPrincipalByName("apress");
			// Get the ACL view
			AclFileAttributeView view = Files.getFileAttributeView(path,
					AclFileAttributeView.class);
			// Create a new entry
			AclEntry entry = AclEntry
					.newBuilder()
					.setType(AclEntryType.ALLOW)
					.setPrincipal(user)
					.setPermissions(AclEntryPermission.READ_DATA,
							AclEntryPermission.APPEND_DATA).build();
			// read ACL
			List<AclEntry> acl = view.getAcl();
			// Insert the new entry
			acl.add(0, entry);
			// rewrite ACL
			view.setAcl(acl);
			// or, like this
			// Files.setAttribute(path, "acl:acl", acl, NOFOLLOW_LINKS);
		} catch (IOException e) {
			System.err.println(e);
		}

		// File Store Attributes
		// 获取所有的fifilestore的属性信息
		FileSystem fs1 = FileSystems.getDefault();
		for (FileStore store : fs1.getFileStores()) {
			try {
				long total_space = store.getTotalSpace() / 1024;
				long used_space = (store.getTotalSpace() - store
						.getUnallocatedSpace()) / 1024;
				long available_space = store.getUsableSpace() / 1024;
				boolean is_read_only = store.isReadOnly();
				System.out.println("--- " + store.name() + " --- "
						+ store.type());
				System.out.println("Total space: " + total_space);
				System.out.println("Used space: " + used_space);
				System.out.println("Available space: " + available_space);
				System.out.println("Is read only? " + is_read_only);
			} catch (IOException e) {
				System.err.println(e);
			}
		}

		// 获取某个文件的fifilestore,再查询filestroe的属性信息
		try {
			FileStore store = Files.getFileStore(path);
			FileStoreAttributeView fsav = store
					.getFileStoreAttributeView(FileStoreAttributeView.class);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// User-Defined File Attributes View 用户自定义文件属性
		// 检测文件系统是否支持自定义属性
		try {
			FileStore store = Files.getFileStore(path);
			if (!store
					.supportsFileAttributeView(UserDefinedFileAttributeView.class)) {
				System.out
						.println("The user defined attributes are not supported on: "
								+ store);
			} else {
				System.out
						.println("The user defined attributes are supported on: "
								+ store);
			}
		} catch (IOException e) {
			System.err.println(e);
		}
		// 设置文件属性
		UserDefinedFileAttributeView udfav = Files.getFileAttributeView(path,
				UserDefinedFileAttributeView.class);
		try {
			int written = udfav.write(
					"file.description",
					Charset.defaultCharset().encode(
							"This file contains private information!"));
			System.out.println("write user defined file attribute return :"
					+ written);
		} catch (IOException e) {
			System.err.println(e);
		}
		// 获取文件的所有自定义属性
		try {
			for (String name : udfav.list()) {
				System.out.println(udfav.size(name) + "" + name);
			}
		} catch (IOException e) {
			System.err.println(e);
		}
		try {
			int size = udfav.size("file.description");
			ByteBuffer bb = ByteBuffer.allocateDirect(size);
			udfav.read("file.description", bb);
			bb.flip();
			System.out.println(Charset.defaultCharset().decode(bb).toString());
		} catch (IOException e) {
			System.err.println(e);
		}
		//删除自定义文件属性
		try {
			udfav.delete("file.description");
		} catch (IOException e) {
			System.err.println(e);
		}

	}
}

 在我的文件系统的输出

basic
owner
user
unix
dos
posix
/dev/loop0 ---true
proc ---true
sysfs ---true
none ---true
none ---true
none ---true
udev ---true
devpts ---true
tmpfs ---true
none ---true
none ---true
none ---true
/dev/sda6 ---true
binfmt_misc ---true
gvfsd-fuse ---true
/dev/sda5 ---true
rootfs ---true
File size: 265
File creation time: 2012-12-29T12:53:35Z
File was last accessed at: 2012-12-29T12:53:35Z
File was last modified at: 2012-12-29T12:53:35Z
Is directory? false
Is  regular file? true
Is  symbolic link? false
Is  other? false
Size: 265
Is read only ? false
Is Hidden ? false
Is archive ? false
Is  system ? false
java.nio.file.attribute.UserPrincipalNotFoundException
weijianzhongwj
weijianzhongwj
File owner: weijianzhongwj
java.nio.file.attribute.UserPrincipalNotFoundException
java.nio.file.attribute.UserPrincipalNotFoundException
File group: weijianzhongwj
File permissions: [OWNER_WRITE, OTHERS_READ, GROUP_READ, OWNER_READ]
java.nio.file.FileAlreadyExistsException: /home/weijianzhongwj/www/pyweb.settings
java.nio.file.attribute.UserPrincipalNotFoundException
weijianzhongwj
java.lang.NullPointerException
java.nio.file.attribute.UserPrincipalNotFoundException
--- /dev/loop0 --- ext4
Total space: 29979608
Used space: 17216488
Available space: 11240228
Is read only? false
--- proc --- proc
Total space: 0
Used space: 0
Available space: 0
Is read only? false
--- sysfs --- sysfs
Total space: 0
Used space: 0
Available space: 0
Is read only? false
--- none --- fusectl
Total space: 0
Used space: 0
Available space: 0
Is read only? false
--- none --- debugfs
Total space: 0
Used space: 0
Available space: 0
Is read only? false
--- none --- securityfs
Total space: 0
Used space: 0
Available space: 0
Is read only? false
--- udev --- devtmpfs
Total space: 4063888
Used space: 4
Available space: 4063884
Is read only? false
--- devpts --- devpts
Total space: 0
Used space: 0
Available space: 0
Is read only? false
--- tmpfs --- tmpfs
Total space: 1628652
Used space: 892
Available space: 1627760
Is read only? false
--- none --- tmpfs
Total space: 5120
Used space: 0
Available space: 5120
Is read only? false
--- none --- tmpfs
Total space: 4071628
Used space: 380
Available space: 4071248
Is read only? false
--- none --- tmpfs
Total space: 102400
Used space: 8
Available space: 102392
Is read only? false
--- /dev/sda6 --- fuseblk
Total space: 164089852
Used space: 101256692
Available space: 62833160
Is read only? false
--- binfmt_misc --- binfmt_misc
Total space: 0
Used space: 0
Available space: 0
Is read only? false
--- gvfsd-fuse --- fuse.gvfsd-fuse
Total space: 0
Used space: 0
Available space: 0
Is read only? false
--- /dev/sda5 --- fuseblk
Total space: 102399704
Used space: 81181588
Available space: 21218116
Is read only? false
The user defined attributes are supported on: / (rootfs)
write user defined file attribute return :39
39file.description
This file contains private information!
 
0
8
分享到:
评论
1 楼 宋建勇 2013-01-05  

相关推荐

    Pro Java 7 NIO2

    ### Pro Java 7 NIO2:深入理解Path类与文件系统操作 #### 一、引言 《Pro Java 7 NIO2》是一本专注于Java 7中的新I/O(NIO.2)特性的书籍,它介绍了如何利用Java 7的新特性来处理文件和网络操作。本书的核心在于...

    Java.NIO资源下载资源下载

    本书《Java™ NIO》由 Ron Hitchens 编写,出版社为 O'Reilly,出版于2002年8月,ISBN号为0-596-00288-2,全书共有312页。 ### Java NIO 的优势 本书深入探讨了 Java 1.4 版本中的新 I/O 功能,并通过具体示例展示...

    ProJava7NIO.2PDFBooks.pdf 英文原版

    Pro Java 7 NIO.2 – PDF Books

    java NIO.zip

    Java NIO,全称为Non-Blocking Input/Output(非阻塞输入/输出),是Java标准库提供的一种替代传统的I/O模型的新技术。自Java 1.4版本引入NIO后,它为Java开发者提供了更高效的数据传输方式,尤其是在处理大量并发...

    java基于NIO实现Reactor模型源码.zip

    java基于NIO实现Reactor模型源码java基于NIO实现Reactor模型源码java基于NIO实现Reactor模型源码java基于NIO实现Reactor模型源码java基于NIO实现Reactor模型源码java基于NIO实现Reactor模型源码java基于NIO实现...

    Java NIO 中英文版 + Pro Java 7 NIO.2

    `Pro Java 7 NIO.2`这本书由Anghel Leonard著,深入探讨了Java NIO.2 API,这是Java 7引入的进一步扩展,包括: 1. **文件系统API增强**:新增了AsynchronousFileChannel,支持异步文件操作,可以在后台线程中执行...

    Java IO NIO and NIO 2 无水印pdf

    Java IO NIO and NIO 2 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn...

    Java-NIO2教程

    - **JDK1.7至今**: 随着Java 7的发布,NIO2(New I/O version 2)作为JSR-203的一部分被引入。NIO2提供了一套新的API,支持更为高效的异步I/O操作,并且引入了强大的文件系统API,包括`Path`、`Files`等类,使得文件...

    java NIO详细教程

    ### Java NIO 详细教程知识点解析 #### 一、Java NIO 概述 Java NIO(New IO)是Java平台提供的一种新的IO操作模式,它首次出现在Java 1.4版本中,并在后续版本中不断完善。Java NIO 的设计目的是为了克服传统Java ...

    Pro Java 7 NIO

    在Java 7之前,文件I/O主要通过java.io包实现,而在Java 7及以后版本中,java.nio.file包新增了大量API,为文件I/O带来了更多功能和性能上的优化。比如,书中介绍到如何使用java.nio.file.attribute API来获取和设置...

    Pro Java 7 NIO.2.pdf

    根据提供的文件信息,“Pro Java 7 NIO.2.pdf”由Anghel Leonard于2011年编写,主要介绍了Java 7中的新输入/输出(NIO)API,特别是NIO.2(JSR 203)所带来的增强功能。这本书通过一系列章节详细讲解了如何使用NIO.2...

    PRO JAVA 7 NIO2

    在Java 7的NIO2(JSR203:Java平台上的更多新I/O API)更新中,`java.nio.file.Path` 类成为了核心组件之一,为开发者提供了更高效、更直观的文件系统操作接口。本文将详细解析 `Path` 类的功能与应用,帮助读者掌握...

    java NIO和java并发编程的书籍

    java NIO和java并发编程的书籍java NIO和java并发编程的书籍java NIO和java并发编程的书籍java NIO和java并发编程的书籍java NIO和java并发编程的书籍java NIO和java并发编程的书籍java NIO和java并发编程的书籍java...

    Java IO NIO and NIO 2 epub

    Java IO NIO and NIO 2 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    JavaNIO chm帮助文档

    Java NIO系列教程(一) Java NIO 概述 Java NIO系列教程(二) Channel Java NIO系列教程(三) Buffer Java NIO系列教程(四) Scatter/Gather Java NIO系列教程(五) 通道之间的数据传输 Java NIO系列教程(六)...

    Java IO, NIO and NIO.2

    Java NIO.2在JDK 7中引入,又称为JSR 203。NIO.2进一步改进了Java的I/O能力,主要包括以下三个方面: 1. 改进的文件系统接口(File API):引入了java.nio.file包,其中包括Path、Paths、Files类,提供了更为现代和...

    JAVA-NIO-DEMO

    Java NIO(New IO)是Java 1.4版本引入的一个新模块,它提供了一种不同于传统IO(基于字节流和字符流)的I/O操作方式。传统的IO模型是阻塞式的,而NIO的核心特点是非阻塞,这使得在处理大量并发I/O请求时更为高效。...

    nio.rar_FastCopyFile.java_NIO_UseFloatBuffer.java_java nio_文件锁

    Java NIO(New Input/Output)是Java标准库中提供的一种I/O模型,与传统的BIO( Blocking I/O)相比,NIO具有更好的性能和更高的灵活性。NIO的核心组件包括通道(Channel)、缓冲区(Buffer)和选择器(Selector)。...

Global site tag (gtag.js) - Google Analytics