Path;Paths和Files;FileVisitor
package filet; import java.io.FileOutputStream; import java.nio.file.FileStore; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class FileTest { public static void main(String[] args) throws Exception { //复制文件 Files.copy(Paths.get("C:\\Users\\Administrator\\Desktop\\a.txt"),new FileOutputStream("C:\\Users\\Administrator\\Desktop\\test.txt")); //一次性得到fileTest的所有文件 List<String> lines = Files.readAllLines(Paths.get("C:\\Users\\Administrator\\Desktop\\a.txt")); System.out.println(lines); //复制文件 Files.copy(Paths.get("C:\\Users\\Administrator\\Desktop\\dd.png"),new FileOutputStream("C:\\Users\\Administrator\\Desktop\\ddtest.png")); List<String> pome = new ArrayList<>(); pome.add("aadddd"); pome.add("dfgfdf"); //直接将多个字符串内容写入指定文件 Files.write(Paths.get("C:\\Users\\Administrator\\Desktop\\a.txt"),pome); //使用java8新增的Stream API读取文件内容 Files.list(Paths.get(".")).forEach(path->System.out.println(path)); Files.lines(Paths.get("C:\\Users\\Administrator\\Desktop\\a.txt")).forEach(line->System.out.println(line)); //判断c盘可用空间 FileStore csStore = Files.getFileStore(Paths.get("C:")); System.out.println("C共有空间:"+csStore.getTotalSpace()); System.out.println("C可用空间:"+csStore.getUsableSpace()); } }
使用FileVisitor遍历文件和目录
package filet; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; public class FileVisitorTest { public static void main(String[] args) throws Exception { //遍历该盘下的所有文件和子目录 Files.walkFileTree(Paths.get("C:\\Users\\Administrator\\Desktop"), new SimpleFileVisitor<Path>() { //访问文件时触发该方法 @Override public FileVisitResult visitFile(Path file,BasicFileAttributes attrs) { System.out.println("正在访问"+file+"文件"); //找到了File if(file.endsWith("a.txt")) { System.out.println("已找到目标文件"); return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; } //开始访问目标目录时触发该方法 @Override public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs) { System.out.println("正在访问:"+dir+"路径"); return FileVisitResult.CONTINUE; } }); } }