Path,Paths,Files这三个类的加入使得对普通文件的处理更加快捷。让程序猿从FileOutputStream,BufferedInputStream等复杂的流操作中解救出来。
Path p=Paths.get("F:\\emp.txt");
byte[] by=Files.readAllBytes(p);
String con=new String(by,"UTF-8");
两句话便完成了对一个文件的读入,第三句话是将文件当字符串读入。
对于文件的移动,也变得简单了不少。复制也同理,将move改为copy。
值得注意的是:如果目标文件已经存在,则会移动失败,若是要覆盖原有文件,可以使用REPLACE_EXISTING选项。
Files.move(from, to,StandardCopyOption.REPLACE_EXISTING);
若是想要复制所有文件属性,可以使用COPY_ATTRIBUTES.
Path from=Paths.get("F:\\emp.txt");
Path to=Paths.get("G:\\move.txt");
Files.move(from, to);
删除文件:Files.delete(path);若目标文件不存在抛异常。Files.deleteIfExists(path);若目标不存在会返回false。
创建新目录:Files.createDirectory(path);
创建新文件:Files.createFile(path);
Files类还可以获取文件信息。
如函数static boolean exists(path);等,详情见官方文档:官方Files介绍
Files可以高效地获取一个目录中所有文件(相对于File的方法高效地多)
DirectoryStreamentries = Files.newDirectoryStream(path);
for(Path entry:entries)
{
System.out.println(entry);
}
并且,若是想要过滤文件也是可以的
常见的用法:
// 复制文件
Files.copy(Paths.get("FilesTest.java")
, new FileOutputStream("a.txt"));
// 判断FilesTest.java文件是否为隐藏文件
System.out.println("FilesTest.java是否为隐藏文件:"
+ Files.isHidden(Paths.get("FilesTest.java")));
// 一次性读取FilesTest.java文件的所有行
List lines = Files.readAllLines(Paths
.get("FilesTest.java"), Charset.forName("gbk"));
System.out.println(lines);
// 判断指定文件的大小
System.out.println("FilesTest.java的大小为:"
+ Files.size(Paths.get("FilesTest.java")));
List poem = new ArrayList<>();
poem.add("水晶潭底银鱼跃");
poem.add("清徐风中碧竿横");
// 直接将多个字符串内容写入指定文件中
Files.write(Paths.get("pome.txt") , poem
, Charset.forName("gbk"));
FileStore cStore = Files.getFileStore(Paths.get("C:"));
// 判断C盘的总空间,可用空间
System.out.println("C:共有空间:" + cStore.getTotalSpace());
System.out.println("C:可用空间:" + cStore.getUsableSpace());
通过继承SimpleFileVisitor,便可以实现访问目录下所有子目录。
或者调用Files.walkFileTree(Path start,FileVisitor super Path>visitor) 实现一个匿名内部类。
public class FileVisitorTest
{
public static void main(String[] args)
throws Exception
{
// 遍历g:\publish\codes\15目录下的所有文件和子目录
Files.walkFileTree(Paths.get("g:", "publish" , "codes" , "15")
, new SimpleFileVisitor()
{
// 访问文件时候触发该方法
@Override
public FileVisitResult visitFile(Path file
, BasicFileAttributes attrs) throws IOException
{
System.out.println("正在访问" + file + "文件");
// 找到了FileInputStreamTest.java文件
if (file.endsWith("FileInputStreamTest.java"))
{
System.out.println("--已经找到目标文件--");
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
// 开始访问目录时触发该方法
@Override
public FileVisitResult preVisitDirectory(Path dir
, BasicFileAttributes attrs) throws IOException
{
System.out.println("正在访问:" + dir + " 路径");
return FileVisitResult.CONTINUE;
}
});
}}
WatchService watch =FileSystems.getDefault().newWatchService();
Path p=Paths.get("C:/");
p.register(watch,StandardWatchEventKinds.ENTRY_CREATE);
while(true) {
WatchKey key = watch.take();
for (WatchEvent event: key.pollEvents()) {
System.out.println("context:"+event.context()+" kind:"+event.kind());
}
}
// 获取将要操作的文件
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 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("发行者", Charset.defaultCharset()
.encode("疯狂Java联盟"));
// 获取访问DOS属性的DosFileAttributeView
DosFileAttributeView dosView = Files.getFileAttributeView(testPath
, DosFileAttributeView.class);
// 将文件设置隐藏、只读
dosView.setHidden(true);
dosView.setReadOnly(true);