
-
path and filePath are absolute paths which begin with '/' and do not end with '/' except that the path is just "/".
public class FileSystem {
class File {
boolean isfile = false;
HashMap<String, File> files = new HashMap<>();
String content = "";
}
File root;
public FileSystem() {
root = new File();
}
public List<String> ls(String path) {
File f = root;
List<String> files = new ArrayList<>();
if (!path.equals("/")) {
String[] arr = path.split("/");
for (int i = 1; i < arr.length; i++) {
f = f.files.get(arr[i]);
}
if (f.isfile) {
files.add(arr[arr.length - 1]);
return files;
}
}
List<String> res = new ArrayList<>(f.files.keySet());
Collections.sort(res);
return res;
}
public void mkdir(String path) {
File f = root;
String[] arr = path.split("/");
for (int i = 1; i < arr.length; i++) {
if (!f.files.containsKey(arr[i])) {
f.files.put(arr[i], new File());
}
f = f.files.get(arr[i]);
}
}
public void addContentToFile(String filePath, String content) {
File f = root;
String[] arr = filePath.split("/");
for (int i = 1; i < arr.length - 1; i++) {
f = f.files.get(arr[i]);
}
if (!f.files.containsKey(arr[arr.length - 1])) {
f.files.put(arr[arr.length - 1], new File());
}
f = f.files.get(arr[arr.length - 1]);
f.isfile = true;
f.content += content;
}
public String readContentFromFile(String filePath) {
File f = root;
String[] arr = filePath.split("/");
for (int i = 1; i < arr.length - 1; i++) {
f = f.files.get(arr[i]);
}
return f.files.get(arr[arr.length - 1]).content;
}
}