I've a code that goes like this:
public static void displayDirectoryContents(File dir) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory() && !file.getName().endsWith(".svn")) {
System.out.println("directory:" + file.getCanonicalPath());
displayDirectoryContents(file);
} else {
System.out.println("file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Now, is there a way to put the result set into a hashmap?
You have lots of nesting of objects, so hashmap could be not so good data structure. I would suggest to introduce the custom POJO and tree-like structure:
class Node { String canonicalPath; String type; Node parent; List<Node> children = new ArrayList<>(); }
And modified your code :
public List<Node> displayDirectoryContents(File dir, Node parent) {
List<Node> result = new ArrayList<Node>();
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory() && !file.getName().endsWith(".svn")) {
Node directory = new Node(file.getCanonicalPath(), "directory", parent);
directory.setChildren(displayDirectoryContents(file, directory);
result.add( directory );
} else {
result.add(new Node(file.getCanonicalPath(), "file", parent);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
something like that - and modify than your processing.
or if you need file list with its names :
you can introduce Map<String, Object>
, and as Object
you can put either String
(for file), or Map<String, Object>
for folder, and make recursion.
or simply make a List
of files, and recursively populate it. with pure file paths, like
List<String> displayDirectoryContents(File dir) {
List<String> res = new ArrayList();
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory() && !file.getName().endsWith(".svn")) {
res.add("directory:" + file.getCanonicalPath());
res.addAll(displayDirectoryContents(file));
} else {
res.add("file:" + file.getCanonicalPath());
}
}
return res;
}
and than you can:
displayDirectoryContents("/dummypath").forEach(System.out.println);
will give you the same result.
Or to Concurrent map of string-string
Map<String, String> res = displayDirectoryContents("/dummypath").stream().collect(Collectors.toConcurrentMap(o -> o, o -> o));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.