Java - mkdir() not writing directory

后端 未结 2 437
误落风尘
误落风尘 2020-12-11 16:14

I am trying to create a directory but it seems to fail every time? I have checked that it is not a permission issue too, I have full permission to write to that directory. T

2条回答
  •  春和景丽
    2020-12-11 16:47

    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

提交回复
热议问题