-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.java
More file actions
81 lines (72 loc) · 1.89 KB
/
Tree.java
File metadata and controls
81 lines (72 loc) · 1.89 KB
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
package il.co.ilrd.compositetree;
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.NotDirectoryException;
public class Tree {
private CompositeFolder root;
public Tree(String path) throws FileNotFoundException, NotDirectoryException {
if (new File(path).exists() == false) {
throw new FileNotFoundException();
} if (new File(path).isFile()) {
throw new NotDirectoryException("You've entered a file path.");
}
root = new CompositeFolder(path);
}
public void PrintTree() {
root.Print(0);
}
private abstract class Component {
String name;
abstract void Print(int depth);
}
private class CompositeFolder extends Component {
private List<Component> paths;
private CompositeFolder(String path) {
File file = new File(path);
this.name = file.getName();
paths = new ArrayList<Component>();
for (File f : file.listFiles())
{
if (f.isDirectory()) {
paths.add(new CompositeFolder(f.getAbsolutePath()));
} else {
paths.add(new CompositeFile(f.getAbsolutePath()));
}
}
}
@Override
void Print(int depth) {
for (int i = 0; i < depth; ++i) {
System.out.print(" ");
}
System.out.println(name);
for (Component c : paths) {
c.Print(depth + 1);
}
}
}
private class CompositeFile extends Component {
private CompositeFile(String path) {
File file = new File(path);
this.name = file.getName();
}
@Override
void Print(int depth) {
for (int i = 0; i < depth; ++i) {
System.out.print(" ");
}
System.out.println("└── " + name);
}
}
public static void main(String[] args) {
try {
String path = "/home/ifat/ifat-ori/fs/projects/src/il/co/ilrd";
Tree tree = new Tree(path);
tree.PrintTree();
} catch (FileNotFoundException | NotDirectoryException e) {
System.out.println("invalid path");
}
}
}