Java Files 常用方法
所属分类 java
浏览量 568
java.nio.file.Files
public static boolean isExecutable(Path path)
public static boolean isRegularFile(Path path, LinkOption... options)
public static boolean isDirectory(Path path, LinkOption... options)
public static boolean isSymbolicLink(Path path)
boolean exist = Files.exists(Paths.get(path));
boolean notExist = Files.notExists(Paths.get(path));
Files.delete(Paths.get(path));
Files.deleteIfExists(Paths.get(path));
NoSuchFileException
DirectoryNotEmptyException
Files.createDirectories(Paths.get(path));
Files.createFile(Paths.get(file));
List< String> list = new ArrayList< >();
list.add("this is title");
list.add("this is content");
Files.write(Paths.get(path), list, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
Files.write(Paths.get(path), "this is context".getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
StandardOpenOption.APPEND 追加
StandardOpenOption.CREATE 文件不存在则创建
默认使用UTF-8
List< String> list1 = Files.readAllLines(Paths.get("/path/file.txt"), StandardCharsets.UTF_8);
List< String> list2 = Files.readAllLines(Paths.get("/path/file.txt"), Charset.forName("UTF-8"));
List< String> list3 = Files.readAllLines(Paths.get("/path/file.txt"), Charset.defaultCharset());
按行读取
String file = "/path/file.txt";
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(reader);) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
递归删除文件及文件夹
String path = "/path/dir";
Files.walk(Paths.get(path))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
Files.walkFileTree 遍历删除
String path = "/path/dir";
Files.walkFileTree(Paths.get(path), new SimpleFileVisitor() {
// 访问文件时
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
System.out.printf("文件被删除 : %s%n", file);
return FileVisitResult.CONTINUE;
}
// 访问子目录前
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
System.out.printf("正在访问目录 : %s%n", dir);
return FileVisitResult.CONTINUE;
}
// 访问目录之后
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
System.out.printf("文件夹被删除: %s%n", dir);
return FileVisitResult.CONTINUE;
}
// 访问失败时
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println("visitFileFailed "+exc);
return super.visitFileFailed(file, exc);
}
}
);
上一篇
下一篇
知识点汇总
Spring中的设计模式
设计模式之Facade
hibernate Session get()和load()方法区别
hibernate5.3 tutorials
hibernate5 主键生成策略