View Javadoc
1   /*
2    * This file is part of ***  M y C o R e  ***
3    * See http://www.mycore.de/ for details.
4    *
5    * MyCoRe is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * MyCoRe is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
17   */
18  
19  package org.mycore.datamodel.niofs.utils;
20  
21  import java.io.IOException;
22  import java.nio.file.FileVisitResult;
23  import java.nio.file.FileVisitor;
24  import java.nio.file.Files;
25  import java.nio.file.Path;
26  import java.nio.file.SimpleFileVisitor;
27  import java.nio.file.attribute.BasicFileAttributes;
28  
29  /**
30   * A {@link FileVisitor} to delete a directory recursivly
31   * <pre>
32   *   Files.walkFileTree(rootPath, MCRRecursiveDeleter.instance())
33   * </pre>
34   * @author Thomas Scheffler (yagee)
35   *
36   */
37  public final class MCRRecursiveDeleter extends SimpleFileVisitor<Path> {
38  
39      private static final MCRRecursiveDeleter INSTANCE = new MCRRecursiveDeleter();
40  
41      private MCRRecursiveDeleter() {
42      }
43  
44      public static MCRRecursiveDeleter instance() {
45          return INSTANCE;
46      }
47  
48      @Override
49      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
50          Files.delete(file);
51          return super.visitFile(file, attrs);
52      }
53  
54      @Override
55      public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
56          if (exc != null) {
57              throw exc;
58          }
59          if (dir.getNameCount() > 0) {
60              Files.delete(dir);
61          }
62          return super.postVisitDirectory(dir, exc);
63      }
64  }