我目前正在研究一种创建文件和目录的方法。下面是用例和问题的解释。
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/