85 lines
2.5 KiB
Java
85 lines
2.5 KiB
Java
package de.nclazz.commons.io;
|
|
|
|
import lombok.NonNull;
|
|
import lombok.SneakyThrows;
|
|
|
|
import java.io.File;
|
|
import java.io.IOException;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.nio.file.attribute.FileAttribute;
|
|
import java.util.function.Consumer;
|
|
|
|
public abstract class FileUtils {
|
|
|
|
private FileUtils() { /* no-op */ }
|
|
|
|
/**
|
|
* Deletes a directory recursively.
|
|
* @param dir Directory to delete
|
|
* @throws NullPointerException if {@code dir} is {@code null}
|
|
* @throws IllegalArgumentException if {@code dir} is not a directory
|
|
*/
|
|
public static void deleteDirectoryRecursively(@NonNull File dir) {
|
|
if(!dir.exists()) return;
|
|
if(!dir.isDirectory()) {
|
|
throw new IllegalArgumentException(String.format("File '%s' is not a directory!", dir.getAbsolutePath()));
|
|
}
|
|
|
|
for(File file : dir.listFiles()) {
|
|
if(file.isDirectory()) {
|
|
deleteDirectoryRecursively(file);
|
|
}else {
|
|
file.delete();
|
|
}
|
|
}
|
|
|
|
dir.delete();
|
|
}
|
|
|
|
/**
|
|
* Creates a temporary directory and passes it to {@code dirConsumer}.
|
|
* After the consumer returns the directory will be deleted.
|
|
*
|
|
* Attention: never store the given {@code File} instance in an external
|
|
* variable, as it will definately be deleted, after the {@code Consumer} returns!
|
|
* @param dirConsumer
|
|
*/
|
|
@SneakyThrows
|
|
public static void withTempDirectory(String prefix, @NonNull Consumer<File> dirConsumer) {
|
|
Path path = Files.createTempDirectory(prefix);
|
|
File dir = path.toFile();
|
|
|
|
dirConsumer.accept(dir);
|
|
|
|
if(dir.exists()) {
|
|
deleteDirectoryRecursively(dir);
|
|
}
|
|
}
|
|
|
|
public static void withTempDirectory(Consumer<File> dirConsumer) {
|
|
withTempDirectory("nclazz", dirConsumer);
|
|
}
|
|
|
|
/**
|
|
* Creates a temporary file and passes it to {@code fileConsumer}.
|
|
* After the consumer returns the directory will be deleted.
|
|
*
|
|
* Attention: never store the given {@code File} instance in an external
|
|
* variable, as it will definitely be deleted, after the {@code Consumer} returns!
|
|
* @param fileConsumer
|
|
*/
|
|
@SneakyThrows
|
|
public static void withTempFile(String prefix, String suffix, @NonNull Consumer<File> fileConsumer) {
|
|
Path path = Files.createTempFile(prefix, suffix);
|
|
File file = path.toFile();
|
|
|
|
fileConsumer.accept(file);
|
|
|
|
if(file.exists()) {
|
|
file.delete();
|
|
}
|
|
}
|
|
|
|
}
|