Path接口与Files工具类
1.path接口
Path表示的是一个目录名序列,其后还可以跟着一个文件名,路径中的第一个部件是跟部件时就是绝对路径。否则就是相对路径
2.Files工具类
读写文件:static path write(Path path,byte[] bytes,OpenOption...options)
写入文件
static byte[] readAllBytes(Path path)
读取文件中的所有字节
复制、剪切,删除
static path copy(Path source,Path target,CopyOption...options)
static path move(Path source,Path target,CopyOption...options)
static void delete(Path path)
//如果不存在会抛出异常,此时调用下面的比较好
static boolean deleteIfExists(Path path)
创建文件和目录
Files.createDirectory(Path)
//创建目录,除了最后一个部件,其他的部件必须存在
Files.createDirectoties(Path)
// 可以创建不存在的中间部件
```Files.cteatFile(Path)``// 创建一个空文件,已经存在会抛出异常
代码演示:
Path:
创建path的三种方式:
File file = new File("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\nio.txt"); Path path2 = file.toPath();
Path path1 = Paths.get("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\nio.txt");
Path path3 = FileSystems.getDefault().getPath("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\nio.txt");
Files:
写文件:
//写文件(Files工具类) try { Files.write(path1, "lalala".getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { e.printStackTrace(); }
读文件
// 读文件 byte[] bytes = new byte[0]; try { bytes = Files.readAllBytes(path1); } catch (IOException e) { e.printStackTrace(); } System.out.println(new String(bytes));
复制文件:
// 复制文件到哪里 Path newPath = Paths.get("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\newNio.txt"); try { //如果存在则覆盖 Files.copy(path1, newPath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); }
移动文件:
// 移动文件 try { Files.move(Paths.get("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\move.txt"), Paths.get("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\NewMove.txt"), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); }
删除文件:
// 删除文件 try { Files.deleteIfExists(Paths.get("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\delete.txt")); } catch (IOException e) { e.printStackTrace(); }
创建新目录
// 创建新目录(除了最后一个目录,其他目录必须存在) // createDirectories(能创建不存在的中间部件) try { Files.createDirectory(Paths.get("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\textDirector")); } catch (IOException e) { e.printStackTrace(); }
创建文件
// 创建文件 try { Files.createFile(Paths.get("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\wenjian.txt")); } catch (IOException e) { e.printStackTrace(); } }