package com.cadrlife.devsearch.agent.service; import com.google.common.base.Throwables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; public class CleanService { private static final Logger LOG = LoggerFactory.getLogger(CleanService.class); public void clean(Path path) { try { LOG.debug("Clean: recursively deleting '{}'", path); if (!path.toFile().exists()) { LOG.debug("Clean: Path does not exist. Done.", path); return; } Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { deleteFile(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { throw exc; } } }); } catch (IOException e) { Throwables.propagate(e); } } private void deleteFile(Path file) throws IOException { try { Files.setAttribute(file, "dos:readonly", false); } catch (IllegalArgumentException e) { e.printStackTrace(); } Files.delete(file); } }