readfile - read folder structure from a text file and create the structure - java -
i have text file content below list folder structure:
/root1 /folder1 /file1 /folder2 /file1 /folder3 /file1 /root2 /folder1 /file1 /folder2 /file1 /folder3 /file1
is there better way implement java program solving kind of problem? or have read through each line in file?
i new java not sure better libraries there reading files in java.
thank you.
i think quite specific task, , don't know libraries out of box. main idea want keep note of current ancestors of processed line. can stack. wanted find out if algorithm works coded , work :) hope helps.
import java.io.file; import java.io.ioexception; import java.util.arraylist; import java.util.list; import java.util.scanner; import java.util.stack; public class dirstucturereader { private static final int indentation = 4; public static void main(string[] args) throws exception { directory result = new dirstucturereader().read(new file("testfile.txt")); system.out.println(result); } public directory read(file file) throws ioexception { scanner scanner = new scanner(file); stack<directory> directorystack = new stack<>(); directory root = new directory("/"); // root directory directorystack.add(root); while (scanner.hasnextline()) { processline(scanner.nextline(), directorystack); } return root; } private void processline(string line, stack<directory> directorystack) { int nleadingspaces = getnumberofleadingspaces(line); if (nleadingspaces == -1) return; int depth = nleadingspaces / indentation; while (directorystack.size() > depth + 1) { directorystack.pop(); // discard elements stack when deep , jump 1 or more levels } string dirname = line.substring(nleadingspaces + 1); directory directory = new directory(dirname); directorystack.peek().getchildren().add(directory); // add directory children of proper parent dir directorystack.push(directory); } private int getnumberofleadingspaces(string line) { (int = 0; < line.length(); i++) { if (line.charat(i) != ' ') return i; } return -1; } public static class directory { private list<directory> children = new arraylist<>(); private final string name; public directory(string name) { this.name = name; } public string getname() { return name; } public list<directory> getchildren() { return children; } } }
Comments
Post a Comment