From 993b6df3fea768edee0b521edfc5fff658a22ce8 Mon Sep 17 00:00:00 2001 From: MrPowers Date: Tue, 15 Oct 2019 13:00:44 +0200 Subject: [PATCH] Add NIO helper methods --- .../mrpowers/spark/daria/utils/NioUtils.scala | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/scala/com/github/mrpowers/spark/daria/utils/NioUtils.scala diff --git a/src/main/scala/com/github/mrpowers/spark/daria/utils/NioUtils.scala b/src/main/scala/com/github/mrpowers/spark/daria/utils/NioUtils.scala new file mode 100644 index 00000000..d7e0f0d1 --- /dev/null +++ b/src/main/scala/com/github/mrpowers/spark/daria/utils/NioUtils.scala @@ -0,0 +1,35 @@ +package com.github.mrpowers.spark.daria.utils + +import java.io.IOException +import java.nio.file.{Files, Paths, Path, SimpleFileVisitor, FileVisitResult} +import java.nio.file.attribute.BasicFileAttributes + +// Copied from StackOverflow: https://stackoverflow.com/a/47380288/1125159 +// Per Vladimir Matveev, it's best to use the Java NIO.2 API for modern Java I/O +object NioUtils { + + def remove(root: Path, deleteRoot: Boolean = true): Unit = + Files.walkFileTree( + root, + new SimpleFileVisitor[Path] { + override def visitFile(file: Path, attributes: BasicFileAttributes): FileVisitResult = { + Files.delete(file) + FileVisitResult.CONTINUE + } + + override def postVisitDirectory(dir: Path, exception: IOException): FileVisitResult = { + if (deleteRoot) Files.delete(dir) + FileVisitResult.CONTINUE + } + } + ) + + def removeUnder(string: String): Unit = remove(Paths.get(string), deleteRoot = false) + + def removeAll(string: String): Unit = remove(Paths.get(string)) + + def removeUnder(file: java.io.File): Unit = remove(file.toPath, deleteRoot = false) + + def removeAll(file: java.io.File): Unit = remove(file.toPath) + +}