`

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

    java nio2, Pro Java 7 NIO2

    ProJava7NIO.2PDFBooks.pdf 英文原版

    Pro Java 7 NIO.2 – PDF Books

    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

    Java NIO,Ron Hitchens 著,中文版 裴小星 译,Pro Java 7 NIO.2,Anghel Leonard 著,pdf文字版带书签,无安全限制

    Java IO NIO and NIO 2 无水印pdf

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

    PRO JAVA 7 NIO2

    PRO JAVA 7 NIO2

    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 NIO详细教程

    java NIO详细教程,包括使用背景,实现原理,代码实现

    Pro Java 7 NIO.2.pdf

    Pro Java 7 NIO.2.pdf,2011 by Anghel Leonard

    java nio 实现socket

    java nio 实现socketjava nio 实现socketjava nio 实现socketjava nio 实现socketjava nio 实现socket

    Java-NIO2教程

    比较详尽地介绍了JDK1.7开始支持的NIO2技术。 有兴趣的开发者可以了解一下。

    pro_java_7_nio.2.pdf

    详细介绍java7中新的nio,英文原版pdf,绝对清晰,非扫描版

    Java NIO 中文 Java NIO 中文 Java NIO 中文文档

    Java NIO 深入探讨了 1.4 版的 I/O 新特性,并告诉您如何使用这些特性来极大地提升您所写的 Java 代码的执行效率。这本小册子就程序员所面临的有代表性的 I/O 问题作了详尽阐述,并讲解了 如何才能充分利用新的 I/O ...

    java nio 包读取超大数据文件

    Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据...

    Java NIO英文高清原版

    Java NIO英文高清原版

    java_nio学习文档

    java_nio学习文档

    Java_NIO类库Selector机制解析.doc

    Java_NIO类库Selector机制解析.docJava_NIO类库Selector机制解析.docJava_NIO类库Selector机制解析.docJava_NIO类库Selector机制解析.doc

    java NIO 中文版

    讲解了 JavaIO 与 JAVA NIO区别,JAVA NIO设计理念,以及JDK中java NIO中语法的使用

Global site tag (gtag.js) - Google Analytics