File相关操作,java.nio.file.*

来源:互联网 发布:php人脸识别系统实现 编辑:程序博客网 时间:2024/05/23 01:57

1.获取文件

Path pathFile = Paths.get("e:/dc/MyTest.txt");System.out.println(pathFile.getFileName());System.out.println(Files.getLastModifiedTime(pathFile));        //文件最后修改时间System.out.println(Files.size(pathFile));                       //文件大小System.out.println(Files.isSymbolicLink(pathFile));             //是否是符号链接System.out.println(Files.isDirectory(listings));                //文件是否是目录System.out.println(Files.readAttributes(pathFile,"*"));            //读取文件所有属性

//通过搜索目录找到相应的文件

Path listings = Paths.get("E:/workspace_IJ/HelloTest/src");Files.walkFileTree(listings, new FindJavaFile());
private static class FindJavaFile extends SimpleFileVisitor<Path>{   @Override   public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {      if (file.toString().endsWith(".java")){         System.out.println(file.getFileName());      }      return FileVisitResult.CONTINUE;   }}
得到该目录下的.java文件。
2.操作文件
//创建文件Path target = Paths.get("e:/dc/MyTest.sh");Files.createFile(target);
//复制文件Path source = Paths.get("e:/dc/MyTest.txt");Path target1 = Paths.get("D:/Test/MyTest2.txt");Files.copy( target1,source, StandardCopyOption.REPLACE_EXISTING);      //复制文件操作,最后一个参数表示覆盖即替换已有文件
//移动文件Path target2 = Paths.get("D:/Test/test/MyTest3.txt");Files.move(source, target2,StandardCopyOption.REPLACE_EXISTING);       //移动文件操作
3.监控目录下文件状态
private static void watchFile(){   try {      WatchService watchService = FileSystems.getDefault().newWatchService();      Path dir = FileSystems.getDefault().getPath("D:/Test/");      WatchKey key = dir.register(watchService, new WatchEvent.Kind[]{ENTRY_MODIFY,ENTRY_CREATE,ENTRY_DELETE});      System.out.println(key);      while(1==1){         key = watchService.take();         for(WatchEvent<?> event: key.pollEvents()){            if(event.kind() == ENTRY_MODIFY){               System.out.println("Home dir changed!");               System.out.println(event.context()+"修改了!!!!");            }else if(event.kind() == ENTRY_CREATE){               System.out.println("new file created");               System.out.println(event.context()+"新建了!!!!");            }else if(event.kind() == ENTRY_DELETE){               System.out.println("file has deleted");               System.out.println(event.context()+"被删除了!!!!");            }         }         key.reset();      }   } catch (IOException | InterruptedException e) {      System.out.println(e.getMessage());   }}