Java - mkdir() not writing directory

懵懂的女人 提交于 2019-11-29 13:34:09
La bla bla

It's possibly because File.mkdir creates the directory only if the parent directory exists. Try using File.mkdirs which creates all the necessary directories.

Here's the code which worked for me.

private void writeDir(File f){
    try{
         if(f.mkdirs()) { 
             System.out.println("Directory Created");
        } else {
        System.out.println("Directory is not created");
        }
    } catch(Exception e){
            //  Demo purposes only.  Do NOT do this in real code.  EVER.
            //  It squashes exceptions ...
        e.printStackTrace();
    }
}

The only change I made was to change f.mkdir() to f.mkdirs() and it worked

I think that @La bla bla has nailed it, but just for completeness, here are all of the things that I can think of that could cause a call to File.mkdir() to fail:

  • A syntax error in the pathname; e.g. an illegal character in a file name component
  • The directory to contain the final directory component does not exist.
  • There is already something with that name.
  • You don't have permission to create a directory in the parent directory
  • You don't have permission to do a lookup in some directory on the path
  • The directory to be created is on a read-only file system.
  • The file system gave a hardware error or network related error.

(Obviously, some of these possibilities can be quickly eliminated in the context of this question ...)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!