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

时间:2019-03-16 20:54:40

标签: java file path

我正在尝试一种比较一些根路径和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));

主要问题是我不喜欢它,而且看起来只是为了通过测试而制成的...看起来很糟糕。

在Java中是否有任何内置的解决方案或功能可以使这一点更加清楚。编码这样的感觉就像我正在尝试寻找如何煮沸水。因此,任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

使用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

答案 1 :(得分:0)

您可以仅使用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;
}