访问文件属性

Java7提供了一系列方便的工具类来访问文件的属性,各种工具类都有其不同的作用。
代码例子:

public class AttributeViewTest
{
    public static void main(String[] args)
        throws Exception
    {
        // 获取将要操作的文件
        Path testPath = Paths.get("AttributeViewTest.java");
        // 获取访问基本属性的BasicFileAttributeView
        BasicFileAttributeView basicView = Files.getFileAttributeView(
            testPath , BasicFileAttributeView.class);
        // 获取访问基本属性的BasicFileAttributes
        BasicFileAttributes basicAttribs = basicView.readAttributes();
        // 访问文件的基本属性
        System.out.println("创建时间:" + new Date(basicAttribs
            .creationTime().toMillis()));
        System.out.println("最后访问时间:" + new Date(basicAttribs
            .lastAccessTime().toMillis()));
        System.out.println("最后修改时间:" + new Date(basicAttribs
            .lastModifiedTime().toMillis()));
        System.out.println("文件大小:" + basicAttribs.size());
        // 获取访问文件属主信息的FileOwnerAttributeView
        FileOwnerAttributeView ownerView = Files.getFileAttributeView(
            testPath, FileOwnerAttributeView.class);
        // 获取该文件所属的用户
        System.out.println(ownerView.getOwner());
        // 获取系统中guest对应的用户
        UserPrincipal user = FileSystems.getDefault()
            .getUserPrincipalLookupService()
            .lookupPrincipalByName("guest");
        // 修改用户
        //ownerView.setOwner(user);
        // 获取访问自定义属性的FileOwnerAttributeView
        UserDefinedFileAttributeView userView = Files.getFileAttributeView(
            testPath, UserDefinedFileAttributeView.class);
        List<String> attrNames = userView.list();
        // 遍历所有的自定义属性
        for (String name : attrNames)
        {
            ByteBuffer buf = ByteBuffer.allocate(userView.size(name));
            userView.read(name, buf);
            buf.flip();
            String value = Charset.defaultCharset().decode(buf).toString();
            System.out.println(name + "--->" + value) ;
        }
        // 添加一个自定义属性
        userView.write("beyondboy", Charset.defaultCharset()
            .encode("java"));
        // 获取访问DOS属性的DosFileAttributeView
        DosFileAttributeView dosView = Files.getFileAttributeView(testPath
            , DosFileAttributeView.class);
        // 将文件设置隐藏、只读
        dosView.setHidden(true);
        dosView.setReadOnly(true);
    }
}

第一次运行结果:
创建时间:Wed Mar 04 21:37:11 CST 2015
最后访问时间:Wed Mar 04 21:37:11 CST 2015
最后修改时间:Wed Mar 04 21:44:13 CST 2015
文件大小:2265
Lenovo-PC\Lenovo (User)
在第二次执行之前,由于第一次执行已把AttibuteViewTest.java文件设置隐藏,只读文件,故要把AttibuteViewTest.java文件取消其只读属性,否则会抛出异常,第二次运行结果:
创建时间:Wed Mar 04 21:37:11 CST 2015
最后访问时间:Wed Mar 04 21:37:11 CST 2015
最后修改时间:Wed Mar 04 21:44:13 CST 2015
文件大小:2265
Lenovo-PC\Lenovo (User)
beyondboy—>java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值