1

I want to create a new directory. If it doesn't exist - create it. if it exists - I want to "reset"/"truncate" the directory. In other words, I want to get an empty directory

My problems are -

  1. I read that to check an existence of a directory to decide whether or not to create it is a bad practise, so I can't determine what should I do next. You can read the explanation about why it is a bad practise in How to create a directory in Java?
  2. I can iterate over all the files and delete them, but I'm looking for a more elegant approach.
Paz
  • 1,023
  • 4
  • 14
  • 31
  • 1
    Re 1.: do you access the directory concurrently or not (if you do I don't think there is an atomic way of emptying a directory)? Re 2., that's what is going to happen under the hood anyway. – assylias Jul 31 '17 at 10:08
  • 1
    Have a look at commons-io. E.g. http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#cleanDirectory(java.io.File) – msfoster Jul 31 '17 at 10:11
  • 1
    One thing is certain: do not use `File`. Read the other answers to the question there. They have much information. – RealSkeptic Jul 31 '17 at 10:11
  • I think that I have everything I need in Class FileUtils. Thanks alot – Paz Jul 31 '17 at 10:16

2 Answers2

2

Using some java 8 pattern you have efficiency around directory cleaning and creating ,

File file = new File(path);
    if(!file.exists())
    {

        file.mkdir();
    }
    else
    {            
        Files.walk(Paths.get("C:/test/ABC/"))
        .filter(Files::isRegularFile)
        .map(Path::toFile)
        .forEach(File::delete);
    }
Sohan
  • 6,252
  • 5
  • 35
  • 56
1

Its true that it is a bad practice. As mkdir fails to create directory if same directory name exist. So there is no need of double checking whether a directory with same name exist or not. That is why it is bad practice to check before calling mkdir.

Simple way you can do is to first check if directory exist or not. if so then delete it and call mkdir

You can look into the JDK Bug report. Community members mentioned it as a bug.

NEKIBUR RAHMAN
  • 204
  • 3
  • 15