简单的文件遍历

分别使用java中的ionio遍历文件系统

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package org.zero.example.nio;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class FileExplorer {

public static void main(String[] args) throws IOException {
String uri = "D:\\apps";
walkFileTree(uri);
System.out.println("\n*****************************************************");
showDirFiles(uri);
}

/**
* @param uri 需要遍历的文件系统根目录
*/
private static void showDirFiles(String uri) {
_walkDirFiles(new File(uri), 0);
}

/**
* 使用简单的文件访问,递归遍历 file路径下的所有目录及文件
* @param file
* @param level
*/
private static void _walkDirFiles(File file, int level) {
for(int i=0; i<level; i++) {
System.out.print("\t|");
}
System.out.println(file.getName());
if(file.isDirectory()) {
for(File temp : file.listFiles()) {
_walkDirFiles(temp, level + 1);
}
}
}

/**
* 使用nio包遍历文件系统
* @param uri 需要遍历的文件系统根目录
*/
public static void walkFileTree(String uri) throws IOException {
Path path = Paths.get(uri);
// 当前 uri在文件系统中的深度
final int rootdeep = getLevelByPath(path);
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// 当前遍历的文件在文件系统中的深度
int level = getLevelByPath(file) - rootdeep;
for(int i=0; i<level; i++) {
System.out.print("\t|");
}
System.out.println(file.getFileName().toString());
return super.visitFile(file, attrs);
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
int level = getLevelByPath(dir) - rootdeep;
for(int i=0; i<level; i++) {
System.out.print("\t|");
}
System.out.println(dir.getFileName().toString());
return super.preVisitDirectory(dir, attrs);
}
});
}

private static int getLevelByPath(Path path) {
String separator = File.separator;
if("\\".equals(separator)) { // windows下的 \ 需特殊处理
separator = "\\\\";
}
return path.toString().split(separator).length - 1;
}
}