我正在尝试创建一个方法,比较某些根路径和File完全路径,并将每个目录的名称和完整路径提取为Map。
例如,假设我想要制作一个类似于以下内容的Map:
Map<String, File> mapFile = new HashMap<>;
mapFile.put("root", new File("/root"));
mapFile.put("dir1", new File("/root/dir1"));
mapFile.put("dir2", new File("/root/dir1/dir2"));
mapFile.put("dir3", new File("/root/dir1/dir2/dir3"));以下是我迄今所做的解决方案:
private Map<String, File> fileMap(String rootPath, File file) {
Map<String, File> fileMap = new HashMap<>();
String path = file.getPath().substring(rootPath.length()).replaceAll("\\\\", "/");// fu windows....
String[] chunks = path.split("/");
String p = rootPath.endsWith("/") ? rootPath.substring(0, rootPath.length() - 1) : rootPath;
for (String chunk : chunks) {
if (chunk.isEmpty()) continue;
p += "/" + chunk;
fileMap.put(chunk, new File(p));
}
return fileMap;
}这就是应该如何使用:
Map<String, File> fileMap = fileMap("/root", new File("/root/dir1/dir2/dir3"));
fileMap.forEach((name, path) -> System.out.println(name + ", " + path));主要的问题是我不喜欢它,看起来它只是为了通过tests...And,看起来很糟糕。
是否有任何在Java中构建的解决方案或功能可以使这一点更加清楚。编写这样的代码感觉就像我在努力找出如何煮开水的方法。因此,任何帮助都将不胜感激。谢谢。
发布于 2019-03-16 21:18:43
使用Path类获取目录名:
private static Map<String, File> fileMap(String rootPath, File file) {
Map<String, File> fileMap = new HashMap<>();
fileMap.put(Paths.get(rootPath).getFileName().toString(), new File(rootPath)); // add root path
Path path = file.toPath();
while (!path.equals(Paths.get(rootPath))) {
fileMap.put(path.getFileName().toString(), new File(path.toUri())); // add current dir
path = path.getParent(); // go to parent dir
}
return fileMap;
}甚至可以将Path作为参数直接传递,如下所示
fileMap("/root", new File("/root/dir1/dir2/dir3").toPath());在这种情况下,方法中根本不需要File
发布于 2019-03-16 21:33:28
您只需使用file.getParentFile()方法向下文件路径,直到到达根目录:
private static Map<String, File> fileMap(String rootPath, File file) {
if (!file.getAbsolutePath().startsWith(rootPath)) {
throw new IllegalArgumentException(file.getAbsolutePath() + " is not a child of " + rootPath);
}
File root = new File(rootPath);
Map<String, File> fileMap = new HashMap<>();
while (!root.equals(file)) {
fileMap.put(file.getName(), file);
file = file.getParentFile();
}
fileMap.put(root.getName(), root);
return fileMap;
}https://stackoverflow.com/questions/55201396
复制相似问题