In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.
下面就通过几个简单的操作演示NIO的强大功能吧!
package test.jse.io.nio2.demo1; import java.io.FileOutputStream; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class NIO2Test { public static void main(String[] args) throws Exception { //testPath(); testFiles(); } public static void testPath() { //以当前路径创建Path对象 Path path=Paths.get("."); System.out.println("当前Path对象里包含的路径数量: "+path.getNameCount()); System.out.println("当前Path对象的根路径: "+path.getRoot()); //获取path对应的绝对路径 Path absolutePath=path.toAbsolutePath(); System.out.println("path对应的绝对路径: "+absolutePath); System.out.println("当前absolutePath对象里包含的路径数量: "+absolutePath.getNameCount()); } public static void testFiles() throws Exception { //复制文件 Files.copy(Paths.get("src/test/jse/io/nio2/demo1/NIO2Test.java"),new FileOutputStream("src/test/jse/io/nio2/demo1/new_NIO2Test.java")); //判断NIO2Test.java文件是否为隐藏文件 System.out.println("NIO2Test.java文件是否为隐藏文件:\t"+Files.isHidden(Paths.get("src/test/jse/io/nio2/demo1/NIO2Test.java"))); //一次读取NIO2Test.java文件的所有行 List<String> lines=Files.readAllLines(Paths.get("src/test/jse/io/nio2/demo1/NIO2Test.java"), Charset.forName("gbk")); for (String line : lines) { System.out.println(line); } } }
原文地址:http://blog.csdn.net/sinat_26342009/article/details/45895887