/**
Question Description
Let’s implement an in-memory filesystem with the following interface:
mkdir(path:string)
write_file(path:string, data:string)
read_file(path:string) -> string
The filesystem structure and all data should be stored in the program’s memory.
------------- Clarifications --------------
Path arguments are expected to be well-formed and no validation is required. A well-formed path has a leading slash, and no trailing slash. For example:
/foo/bar
/foo/bar/file.txt
**/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
mkdir - POST
/mkdir?path=/a
payload {
path : string
}
writeFile - POST
/writeFile
payload {
path: "/a"
data: "Hey Felix"
}
readFile - GET
/readFile?path=/a/text.txt
response
{
data: "Hey Felix"
}
*/
public class FileSystem {
Folder root;
public FileSystem(){
this.root = new Folder("root", new HashMap<>(), new HashMap<>());
}
// HashSet<String> directorySet;
// {"/a", "/a/b", "/a/c", "/a/"}
class Folder {
String name;
Map<String, Folder> children;
Map<String, String> files;
public Folder(String name, Map<String, Folder> children, Map<String, String> files) {
this.name = name;
this.children = children;
this.files = files;
}
}
// n
public void makeDirectory(String path) {
Map<String, Folder> children = root.children;
String[] levels = path.split("/");
int n = levels.length;
for (int i = 0; i < n - 1; i++) {
if (children.containsKey(levels[i])) {
// Directory does not exists
throw new IllegalArgumentException("Directory does not exist: " + levels[i]);
}
}
children.put(levels[n-1], new Folder(levels[n-1], new HashMap<>(), new HashMap<>()));
}
public void writeFile(String path, String data) {
String[] levels = path.split("/");
int n = levels.length;
Folder currentFolder = root;
for (int i = 0; i < n-1; i++) {
currentFolder = root.children.get(levels[i]);
}
String fileName = levels[n-1];
currentFolder.files.put(fileName, data);
}
public String readFile(String path) {
String[] levels = path.split("/");
int n = levels.length;
Folder currentFolder = root;
for (int i = 0; i < n-1; i++) {
currentFolder = root.children.get(levels[i]);
}
return currentFolder.files.get(levels[n-1]);
}
public static void main(String args[] ) throws Exception {
FileSystem fs = new FileSystem();
fs.makeDirectory("/a");
fs.makeDirectory("/b");
// Map<String, Folder> rootChildren = fs.root.children;
// for (String key : rootChildren.keySet()) {
// System.out.println("Printing Child: " + key);
// }
fs.writeFile("/a/file.txt", "Hey Felix");
System.out.println(fs.readFile("/a/file.txt"));
}
}