Pra*_*man 5 java tree-structure filereader
我必须解析以下文本文件中给出的一组目录:
# 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
Run Code Online (Sandbox Code Playgroud)
上面的文件用这种方式描述了目录结构:
A
|
+ B
|
+ C
| |
| + D
| |
| + E
| |
| + F
| | |
| | + G
Run Code Online (Sandbox Code Playgroud)
假设开头的行#是注释,我现在有以下代码:
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 + ".");
}
}
Run Code Online (Sandbox Code Playgroud)
所以,这只是显示目录的工作,而不是以分层方式来解析它们.它只是给出了文本表示的输出,这样:
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.
Run Code Online (Sandbox Code Playgroud)
如果它是PHP,我可以将它转换为JSON节点并且可以以分层方式解析父节点或兄弟节点,但我不确定我应该如何在Java中实现它.任何抬头都对我很好.
现在,我用这种方式为树结构创建了一个类:
public class Directory {
private String name;
private Directory parent;
}
Run Code Online (Sandbox Code Playgroud)
但我不知道如何将目录链接为主Java程序中的链接列表.任何帮助在这里将不胜感激.所以,当我在这里做某种树结构时,我想实现类似目录遍历程序的东西.
比方说,如果我把输入作为DirectoryParser C,那么,它应该输出像我这样的东西:
C
|
+ D
|
+ E
|
+ F
| |
| + G
Run Code Online (Sandbox Code Playgroud)
我的当前做法有可能吗?有人可以指导我如何实现这一目标吗?提前致谢.
免责声明:我经历了Java树数据结构?,但我不应该使用任何外部插件在单个文件中获得简单的东西.:(
好吧,伙计们,我为此采用了相同的旧方法。我用 anIterator来遍历ArrayList并这样使用它:
static void RecursiveFolderFinder(String Root)
{
Iterator<Folder> Folder = ListOfFolders.iterator();
while (Folder.hasNext())
{
Folder curFolder = Folder.next();
if (curFolder.getParent().equals(Root))
{
OutputList += " " + curFolder.getName() + " ";
OutputList += "{";
RecursiveFolderFinder(curFolder.getName());
if (OutputList.substring(OutputList.length()-1, OutputList.length()).equals("{"))
OutputList = OutputList.substring(0, OutputList.length()-1);
else if (!OutputList.substring(OutputList.length()-1, OutputList.length()).equals(" "))
OutputList += " }";
else
OutputList += "}";
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道,这种字符串操作是疯狂和无力的,我用他的来确定,没有人用这么有趣的!只是讽刺。感谢@mrhobo的回答。如果有人可以建议我更好的输出,那就太棒了!
| 归档时间: |
|
| 查看次数: |
2213 次 |
| 最近记录: |