首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建从根目录到文件完整路径的映射

如何创建从根目录到文件完整路径的映射
EN

Stack Overflow用户
提问于 2019-03-16 20:54:40
回答 2查看 531关注 0票数 1

我正在尝试创建一个方法,比较某些根路径和File完全路径,并将每个目录的名称和完整路径提取为Map

例如,假设我想要制作一个类似于以下内容的Map

代码语言:javascript
复制
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"));

以下是我迄今所做的解决方案:

代码语言:javascript
复制
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;
}

这就是应该如何使用:

代码语言:javascript
复制
Map<String, File> fileMap = fileMap("/root", new File("/root/dir1/dir2/dir3"));
fileMap.forEach((name, path) -> System.out.println(name + ", " + path));

主要的问题是我不喜欢它,看起来它只是为了通过tests...And,看起来很糟糕。

是否有任何在Java中构建的解决方案或功能可以使这一点更加清楚。编写这样的代码感觉就像我在努力找出如何煮开水的方法。因此,任何帮助都将不胜感激。谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-16 21:18:43

使用Path类获取目录名:

代码语言:javascript
复制
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作为参数直接传递,如下所示

代码语言:javascript
复制
fileMap("/root", new File("/root/dir1/dir2/dir3").toPath());

在这种情况下,方法中根本不需要File

票数 1
EN

Stack Overflow用户

发布于 2019-03-16 21:33:28

您只需使用file.getParentFile()方法向下文件路径,直到到达根目录:

代码语言:javascript
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55201396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档