我想根据缩进创建特定文件的路径。我有一个命令可以返回存储库中项目的结构。如下图所示
Requirement
abc.doc
Software
Code
File
aaa.c
bbb.c
我想知道是否可以获取aaa.c的路径为\Software\Code\File。如果您能给我一些如何做到这一点的想法,那将非常有帮助。
最佳答案
保留<缩进大小,具有该缩进的最后一个文件>的映射。对于处理的每一行,在映射中查找带有(当前行缩进 - 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; }
}
关于java - 根据缩进创建文件夹/文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12913629/