I have to parse a set of directories given in the following text file:
# Note: The root folder's parent is labelled as "?"
# Assume all directory has different name
#
A,?
B,A
C,A
D,C
E,C
F,C
G,F
The above file, depicts the directory structure this way:
A
|
+ B
|
+ C
| |
| + D
| |
| + E
| |
| + F
| | |
| | + G
Assuming the lines starting with #
are comments, I have the following code right now:
String line;
BufferedReader f = new BufferedReader(new FileReader(new File("directory.txt")));
while ((line = f.readLine()) != null)
{
if (!line.substring(0, 1).equals("#"))
{
String directory, parent;
directory = line.split(",")[0];
parent = line.split(",")[1];
if (parent.equals("?"))
System.out.println("Directory " + directory + " is the root.");
else
System.out.println("Directory " + directory + " found inside " + parent + ".");
}
}
So, this just does the work of displaying the directories, that too not in a hierarchical way to parse them. It just gives an output of textual representation, this way:
Directory A is the root.
Directory B found inside A.
Directory C found inside A.
Directory D found inside C.
Directory E found inside C.
Directory F found inside C.
Directory G found inside F.
If it was PHP, I can convert it to JSON nodes and can parse the parent or sibling, in a hierarchical way, but I am not sure how am I supposed to make this in Java. Any heads up will be great for me.
For now, I created a class for the tree structure this way:
public class Directory {
private String name;
private Directory parent;
}
But I am not sure how do I link the directories as kind of linked lists in the main Java program. Any help here would be appreciated. So, when I do some kind of tree structure here, I would like to achieve something like a directory traversing program.
Say, if I give the input as DirectoryParser C
, then, it should output me something like:
C
|
+ D
|
+ E
|
+ F
| |
| + G
Is this possible with the current approach of mine? Can someone please guide me in how to achieve this? Thanks in advance.
Disclaimer: I went through Java tree data-structure?, but I am supposed to get something simple in a single file without using any external plugins. :(