Reputation: 739
I want to create the path of a particular file based on the indent. I have a command which returns me the structure of the project in the repository. like as shown below
Requirement
abc.doc
Software
Code
File
aaa.c
bbb.c
I want to know if I can get the path of aaa.c as \Software\Code\File. It would be very helpful if you can give me some ideas how to do this.
Upvotes: 2
Views: 209
Reputation: 200266
Keep a map of <indent size, last file with that indent>. For each line processed, look up in the map the entry with (current line's indent - 1). That is the parent of your current file.
Do note that you'll need some convention to disambiguate files from folders. You could also assume that all leaf nodes (those without children) are files, but in that case there will be no way to represent an empty folder.
A solution that assumes all leaf nodes are files:
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; }
}
Upvotes: 4