gpt4 book ai didi

java - 使用 File 创建包含句点的目录

转载 作者:行者123 更新时间:2023-12-01 06:41:44 24 4
gpt4 key购买 nike

File testDir = new File("C:\temp\test");
testDir.createNewFile();

据我了解,上面将在目录 c:\temp 中创建一个名为 test 的目录

File testDir = new File("C:\temp\test.dir");
testDir.createNewFile();

据我了解,上面将在目录 c:\temp 中创建一个名为 test.dir 的文件

如果我希望 test.dir 实际上是一个目录,我应该对上面的代码做什么?

最佳答案

不,第一个将创建一个常规文件 - 毕竟,这就是您要求它执行的操作:

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.

没有任何内容表明它将创建一个目录。不过,您需要转义反斜杠,否则它会尝试查找 C:<tab>emp<tab>est

如果要创建目录,请使用 File.mkdirFile.mkdirs() 。您仍然需要转义反斜杠:

File testDir = new File("C:\\temp\\test.dir");
bool created = testDir.mkdir();

(也使用 mkdirs 创建父目录。)返回值告诉您它是否实际创建了目录。

关于java - 使用 File 创建包含句点的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4089127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com