文章目录
Paths
- Paths
- Files
- 1、文件复制
- 2、写文件
- 3、读文件
- 4、遍历文件夹
- 5、递归遍历文件夹
用于来表示文件路径和文件 示例:
@Test
public void testPath() throws IOException {
//构造Path类对象
File file = new File("E:/blog");
System.out.println(file.toURI()); // file:/E:/blog/
Path path = file.toPath();
URI uri = URI.create("file:///E:/blog3");
Path path1 = Paths.get(uri);
Path path2 = Paths.get("E:/", "blog1");
Path path3 = Paths.get("E:/blog2");
Path path4 = FileSystems.getDefault().getPath("E:/", "blog4");
//判断是否存在
System.out.println(Files.exists(path));
//如果文件(目录)不存在创建文件
if (!Files.exists(path1)) {
Files.createDirectory(path1);//创建目录
}
if (!Files.exists(path2)) {
Files.createFile(path2);//创建文件
}
}
Files
文件操作工具类。
1、文件复制public static void main(String[] args) throws IOException {
Files.copy(Paths.get("E:/1234/db_wego.sql"),System.out);
Files.copy(System.in,Paths.get("E:/aa.txt"), StandardCopyOption.REPLACE_EXISTING);
Files.copy(Paths.get("E:/1234/db_wego.sql"),Paths.get("E:/aa.txt"),StandardCopyOption.REPLACE_EXISTING);
}
相关方法介绍:
- 从文件复制到文件:Files.copy(Path source, Path target, CopyOption options);
- 从输入流复制到文件:Files.copy(InputStream in, Path target, CopyOption options);
- 从文件复制到输出流:Files.copy(Path source, OutputStream out);
@Test
public void fun4() throws IOException {
BufferedWriter bw = Files.newBufferedWriter(Paths.get("E:/1234/dd.sql"), StandardCharsets.UTF_8);
bw.write("haha");
bw.flush();
bw.close();
}
3、读文件
@Test
public void fun5() throws IOException {//
BufferedReader br = Files.newBufferedReader(Paths.get("E:/1234/db_wego.sql"), StandardCharsets.UTF_8);
//注意:如果指定的字符编码不对,可能会抛出MalformedInputException异常
String res = null;
while ((res = br.readLine()) != null) {
System.out.println(res);
}
br.close();
}
4、遍历文件夹
@Test
public void fun6() throws IOException {
Path path = Paths.get("E:/1234");
//方式一
Files.newDirectoryStream(path)
.forEach(item -> System.out.println(item.getFileName()));
//方式二
Files.list(path).forEach(item -> System.out.println(item.getFileName()));
}
5、递归遍历文件夹
@Test
public void fun7() throws IOException {
Path root = Paths.get("E:/Workspaces/Project/Blog/src/test/java/com/hc");
List result = new LinkedList();
Files.walkFileTree(root, new FindJavaVisitor(result));
result.forEach(System.out::println);
}
private class FindJavaVisitor extends SimpleFileVisitor {
private List res;
public FindJavaVisitor(List result){
this.res = result;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
if(file.toString().endsWith(".java")){
res.add(file.getFileName());
}
return FileVisitResult.CONTINUE;
}
}