我想基于缩进创建特定文件的路径。我有一个命令,它返回存储库中项目的结构。如下图所示
Requirement
abc.doc
Software
Code
File
aaa.c
bbb.c
我想知道我是否可以将aaa.c的路径作为\ Software \ Code \ File。如果你能给我一些如何做到这一点的想法,将会非常有帮助。
答案 0 :(得分:4)
保留<缩进尺寸的地图,带缩进的最后一个文件>。对于处理的每一行,在地图中查找条目(当前行的缩进 - 1)。那是您当前文件的父级。
请注意,您需要一些约定来消除文件夹中的文件歧义。您还可以假设所有叶节点(没有子节点的节点)都是文件,但在这种情况下,将无法表示空文件夹。
假设所有叶节点都是文件的解决方案:
final Map<Integer, FileDesc> history = new HashMap<>();
final Set<File> files = new HashSet<>();
history.put(-1, new FileDesc(basePath, false));
for (String line : inputLines) {
final int indent = indentSize(line);
final String fileName = fileName(line);
final FileDesc
parent = history.get(indent-1),
previous = history.get(indent),
current = new FileDesc(new File(parent.f, fileName), true);
parent.isFile = false;
if (previous != null && previous.isFile) files.add(previous.f);
history.put(indent, current);
}
for (FileDesc desc : history.values())
if (desc.isFile) files.add(desc.f);
class FileDesc {
final File f;
boolean isFile;
FileDesc(File f, boolean isFile) { this.f = f; this.isFile = isFile; }
}