I have implemented an in-memory filesystem - this is a design question from LeetCode. Is there a better OOP approach to represent files and directories? The current code uses a boolean flag isDirectory to distinguish between files and directories and I'm not confident that it is the best approach. See the code below. I'll also be happy to get any other comments about the code - readability, variable and method naming, etc.
class FileSystem {
Inode root;
public FileSystem()
{
root = new Inode("/", true);
}
public List<String> ls(String path)
{
List<String> listing = new ArrayList<>();
String[] queries = path.substring(1).split("/");
Inode node = root;
for(String query: queries)
{
if(query.isEmpty()) // happens when we search root
break;
node = node.children.get(query);
if(node == null)
return listing;
}
if(node.isDirectory)
{
node.children.forEach((name, inode) -> {
listing.add(name);
});
}
else
{
listing.add(node.Name);
}
Collections.sort(listing);
return listing;
}
public void mkdir(String path)
{
String[] subdirs = path.substring(1).split("/");
Inode node = root;
for(String dir: subdirs)
{
if(dir.isEmpty()) // happens when we search root
break;
if(!node.children.containsKey(dir))
node.children.put(dir, new Inode(dir, true));
node = node.children.get(dir);
}
}
public void addContentToFile(String filePath, String content)
{
String[] subdirs = filePath.substring(1).split("/");
Inode node = root;
for(int i=0; i<subdirs.length; i++)
{
if(!node.children.containsKey(subdirs[i]))
{
if(i < subdirs.length-1)
node.children.put(subdirs[i], new Inode(subdirs[i], true));
else
node.children.put(subdirs[i], new Inode(subdirs[i], false));
}
node = node.children.get(subdirs[i]);
}
node.fileContent.append(content);
}
public String readContentFromFile(String filePath)
{
String[] subdirs = filePath.substring(1).split("/");
Inode node = root;
for(String dir: subdirs)
{
node = node.children.get(dir);
}
return node.fileContent.toString();
}
}
// Trie data structure for files and directories
class Inode
{
public String Name;
public boolean isDirectory=true;
public StringBuilder fileContent=null;
public HashMap<String, Inode> children = null;
public Inode(String name, boolean is_dir)
{
this.Name = name;
this.isDirectory = is_dir;
if(!is_dir)
fileContent = new StringBuilder();
if(is_dir && children == null)
children = new HashMap<>();
}
}