Java7中那些新特性 - 3 (文件信息篇)
今天我们来说说在Java7中如何获得文件的信息。我们这里说的文件信息指的是一个文件是否可以被执行,文件的大小,文件所属用户甚至是文件的内容。
使用java.nio.file.Files类来获得文件信息的方式一共有五种:
使用Files和文件信息相关的静态方法,例如isDirectory,来获得具体某种文件信息。使用Files的getAttribute静态方法来获得某一种文件信息。使用readAttributes方法来返回一个包含所有文件信息的Map对象。用一个BasicFileAttributes接口(某个具体实现类)作为参数,调用readAttributes方法来获得一个包含文件信息的BasicFileAttributes对象。使用getFileAttributeView方法,获得一个详尽的文件信息集合。
Java7引入了一系列关于文件视图的接口。一个文件视图(View)简单来说就组织文件(或者文件夹)信息的一种方式。例如AclFileAttributeView,提供了和文件Access Control List (ACL)相关的方法。FileAttributeView接口是其它所有文件信息接口的父接口。java.nio.file.attribute包下关于View的接口如下:
AclFileAttributeView: 用于维护文件的访问控制列表(ACL)和文件所属的一些信息 BasicFileAttributeView: 用于访问文件的一些基本信息,设置和时间相关的一些属性DosFileAttributeView: 为遗留的DOS文件系统而设计FileOwnerAttributeView: 用于维护文件的所属(属于哪个用户)信息PosixFileAttributeView: 用来支持可移植性操作系统接口(Portable Operating System Interface)UserDefinedFileAttributeView: 用来支持用户定义的文件信息
这里我们首先来看看如何获得文件内容的类型。通常情况下文件内容类型可以通过扩展名来获得。例如txt文件是文本文件,exe文件则是Windows下的可执行文件。但我们可以将一个txt文件重命名成exe文件,这并不能改变文件内容的类型。因此通过文件的扩展名来获得其类型有一定的误导性。Files类的probeContentType就是用来获得文件内容类型的。
public static void main(String[] args) throws Exception { displayContentType("D:/home/projects/note.txt"); displayContentType("D:/home/projects/Chapter 2.doc"); displayContentType("D:/home/projects/java.exe"); } static void displayContentType(String pathText) throws Exception { Path path = Paths.get(pathText); String type = Files.probeContentType(path); System.out.println(type); }public static void main(String[] args) { try { Path path = Paths.get("D:/home/projects/note.txt"); System.out.println(Files.getAttribute(path, "size")); } catch (IOException ex) { System.out.println("IOException"); }} public static void main(String[] args) { Path path = Paths.get("D:/home/projects/note.txt"); FileSystem fileSystem = path.getFileSystem(); Set<String> supportedViews = fileSystem.supportedFileAttributeViews(); for (String view : supportedViews) { System.out.println(view); } } public static void main(String[] args) { Path path = Paths.get("D:/home/projects/note.txt"); try { BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); System.out.println("Creation Time: " + attributes.creationTime()); System.out.println("Last Accessed Time: " + attributes.lastAccessTime()); System.out.println("Last Modified Time: " + attributes.lastModifiedTime()); System.out.println("File Key: " + attributes.fileKey()); System.out.println("Directory: " + attributes.isDirectory()); System.out.println("Other Type of File: " + attributes.isOther()); System.out.println("Regular File: " + attributes.isRegularFile()); System.out.println("Symbolic File: " + attributes.isSymbolicLink()); System.out.println("Size: " + attributes.size()); } catch (IOException exception) { System.out.println("Attribute error"); } }