【问题标题】:get specific subdirectory in java using paths使用路径获取java中的特定子目录
【发布时间】:2020-05-26 23:12:59
【问题描述】:

获取我当前使用的目录的子目录

Paths.get(currentpath.toString(), "subdirectory");

有没有更好的方法?我特别不喜欢 toString 调用,如果可能的话,我宁愿不使用.toFile()

我尝试在此处搜索此内容,但仅找到有关旧 api 或我当前正在使用的内容或完全不相关的问题的答案。

【问题讨论】:

  • 你想要所有的子目录还是只想要一个特定的子目录?
  • @deHaar 我想要一个特定的。

标签: java directory nio subdirectory


【解决方案1】:

你可以只resolve子目录的名称对着根Path这样:

public static void main(String[] args) {
    // definition of the root directory (adjust according to your system)
    String currentPath = "C:\\";
    Path root = Paths.get(currentPath);

    // get a specific subdirectory by its name
    String specificSubDir = "temp";
    // resolve its name against the root directory
    Path specificSubDirPath = root.resolve(specificSubDir);

    // and check the result
    if (Files.isDirectory(specificSubDirPath)) {
        System.out.println("Path " + specificSubDirPath.toAbsolutePath().toString()
                + " is a directory");
    } else {
        System.err.println("Path " + specificSubDirPath.toAbsolutePath().toString()
                + " is not a directory");
    }
}

因为我有一个目录C:\temp\,所以我系统上的输出是

Path C:\temp is a directory

【讨论】:

  • 谢谢,这正是我想要的,在这种情况下我不熟悉关键字resolve。我也只是浏览PathsFiles
猜你喜欢
  • 1970-01-01
  • 2017-12-24
  • 2017-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-07
  • 2014-09-21
  • 2020-12-06
相关资源
最近更新 更多