简体   繁体   English

Java:为什么不创建最后一个文件夹?

[英]Java: Why doesn't this create the last folder?

public static void VDirectoryMaker(File des) {
        if (!des.exists()) {
            File dest = new File(des.getAbsolutePath().substring(0, des.getAbsolutePath().length()-(des.getName().length())));
            VDirectoryMaker(dest);
            dest.mkdir();
        }
    }

If des equals new File("dir1\\\\dir2\\\\dir3\\\\dir4\\\\dir5") why does it only make all non-existing folders up to dir4? 如果des等于new File("dir1\\\\dir2\\\\dir3\\\\dir4\\\\dir5")为什么只将所有不存在的文件夹设置为dir4? dir5 is never created. dir5永远不会创建。

It's because the last dir5 is treated as file without extension inside the dir4 directory. 这是因为最后一个dir5被视为dir4目录中没有扩展名的文件。

Try adding last backslash, the directories should be created as you expected. 尝试添加最后一个反斜杠,应按预期创建目录。

new File("dir1\\dir2\\dir3\\dir4\\dir5\\")

You should also look at File.mkdirs() . 您还应该查看File.mkdirs()

This code is removing the last part of the path: 这段代码删除了路径的最后一部分:

des.getAbsolutePath().substring(
  0, des.getAbsolutePath().length()-(des.getName().length()))

This would work if your input was a complete file path for a file, eg: 如果您输入的是文件的完整文件路径,则此方法有效,例如:

VDirectoryMaker(new File("dir1\\dir2\\dir3\\dir4\\targetfile.txt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM