Files.exists()
检查给出的Path在文件系统中是否存在。
Files.createDirectory()
创建一个目录
Path path = Paths.get("/usr/local/tmp"); try { Files.createDirectory(path); } catch(FileAlreadyExistsException e){ // 已经存在 } catch (IOException e) { // IO异常 }
Files.copy()
拷贝文件
Files.copy(sourcePath, destPath, copyOption)
copyOption可以使用一它个实现类StandardCopyOption
/** * Replace an existing file if it exists. 如果存在就覆盖 */ REPLACE_EXISTING, /** * Copy attributes to the new file. 带着属性一起拷贝 */ COPY_ATTRIBUTES, /** * Move the file as an atomic file system operation. 如果要拷贝的是符号链接,直接拷贝符号链接本身。 */ ATOMIC_MOVE;
Files.move()
移动文件,类似拷贝
Files.delete()
删除文件或文件夹
删除文件不必多说,如果删除目录,需要目录下不为空。如果执意要删除,可以尝试递归删掉下面的内容,再删除目录。如下:
Path rootPath = Paths.get(FOLDER); try { Files.walkFileTree(rootPath, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { System.out.println("删除文件: " + file.toString()); Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); System.out.println("删除目录: " + dir.toString()); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { e.printStackTrace(); }
Files.walkFileTree()
递归遍历指定Path下的内容
FileVisitor接口:
FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs) throws IOException; FileVisitResult visitFile(T file, BasicFileAttributes attrs) throws IOException; FileVisitResult visitFileFailed(T file, IOException exc) throws IOException; FileVisitResult postVisitDirectory(T dir, IOException exc) throws IOException;