Simple File System in Java

 Key for File System is to use Node and Tree to represent file system. And use DFS to insert/validate node.


import java.util.HashMap;
import java.util.Map;

public class Test {
public static void main(String[] args){
String[] files = {
"/app/assets/html/a.html",
"/app/assets/html/b.html",
"/app/assets/js/c.js",
"/app/assets/js/d.js",
"/app/index.html"
};

Tree tree = new Tree();
for (String file:files){
tree.insertFile(file);
}
System.out.println(tree.checkIfExist("/app/assets/js/c.js"));
System.out.println(tree.checkIfExist("/app/assets/js/d.js"));
tree.printFiles();
}
}
class Node{
String name;
Map<String, Node> children;

Node(String name){
this.name=name;
children = new HashMap<>();
}
}
class Tree{
Node root;
Tree(){
this.root = new Node("");
}

void insertFile(String filePath){
String[] folders = filePath.split("/");
Node cur = root;
for(String folder:folders){
if(!cur.children.containsKey(folder)){
cur.children.put(folder, new Node(folder));
}
cur = cur.children.get(folder);
}
}

boolean checkIfExist(String file){
String[] folders = file.split("/");
Node cur=root;
for(String folder:folders){
if(!cur.children.containsKey(folder)){
return false;
}else{
cur=cur.children.get(folder);
}
}
return true;
}

void printFiles(){
dfsPrint(root,"");
}

void dfsPrint(Node node, String indent) {
if(node.children.isEmpty()){
System.out.println(indent + "-- " + node.name);
return;
}
System.out.println(indent + "-- "+node.name);
for(Node child:node.children.values()){
dfsPrint(child, indent + " ");
}
}
}

Comments