java - 创建文件和目录无法正常工作

标签 java file path

我目前正在研究一种创建文件和目录的方法。下面是用例和问题的解释。

1) 当用户指定路径时,例如“/parent/sub folder/file.txt”,系统应该能够创建目录和 file.txt。 (这个有效)

2) 当用户指定路径时,例如“/parent/sub-folder/”或“/parent/sub-folder”,系统应该能够创建所有目录。 (不起作用),它不会创建“/子文件夹/”或“/子文件夹”作为文件夹,而是创建一个名为“子文件夹”的文件。

这是我的代码

Path path = Paths.get(rootDir+"test/hello/");
    try {
        Files.createDirectories(path.getParent());
        if (!Files.isDirectory(path)) {
            Files.createFile(path);
        } else {
            Files.createDirectory(path);
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

最佳答案

您需要使用 createDirectories(Path) 而不是 createDirectory(path)。如 tutorial 中所述:

To create a directory several levels deep when one or more of the parent directories might not yet exist, you can use the convenience method, createDirectories(Path, FileAttribute). As with the createDirectory(Path, FileAttribute) method, you can specify an optional set of initial file attributes. The following code snippet uses default attributes:

Files.createDirectories(Paths.get("foo/bar/test"));

The directories are created, as needed, from the top down. In the foo/bar/test example, if the foo directory does not exist, it is created. Next, the bar directory is created, if needed, and, finally, the test directory is created.

It is possible for this method to fail after creating some, but not all, of the parent directories.

关于java - 创建文件和目录无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23251357/

相关文章:

eclipse:重建项目和所有库

java - Spring-WS SOAP header 前缀问题

python - 错误的文件描述符错误

file - 检查.exe文件的文件版本(服务器端),以及是否有较新的下载文件

file - 去。将 []byte 写入文件导致零字节文件

c# - 在 silverlight 中淡入淡出路径?

go - Go 中的 path 和 path.filepath 包有什么区别

java - 使用 Eclipse 的 Weblogic 连接池

java - 锁定 Jar 文件,将源文件隐藏在 .jar 文件中

php - 什么路径是可以接受的?