2022-07-20 13:18:57 +02:00
|
|
|
package fr.pandacube.lib.util;
|
2021-03-21 20:17:31 +01:00
|
|
|
|
|
|
|
import java.io.File;
|
|
|
|
import java.io.IOException;
|
|
|
|
import java.nio.file.Files;
|
2022-07-10 00:55:56 +02:00
|
|
|
import java.nio.file.attribute.BasicFileAttributes;
|
2021-03-21 20:17:31 +01:00
|
|
|
|
2022-07-28 01:13:35 +02:00
|
|
|
/**
|
|
|
|
* Provides utility methods to manipulate files and directories
|
|
|
|
*/
|
2021-03-21 20:17:31 +01:00
|
|
|
public class FileUtils {
|
2022-07-28 01:13:35 +02:00
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Recursively delete the provided file and all of its content if it is a directory.
|
|
|
|
* @param target the target file or directory.
|
|
|
|
*/
|
2021-03-21 20:17:31 +01:00
|
|
|
public static void delete(File target) {
|
|
|
|
if (target.isDirectory())
|
|
|
|
for (File child : target.listFiles())
|
|
|
|
delete(child);
|
|
|
|
target.delete();
|
|
|
|
}
|
2022-07-28 01:13:35 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Recursively copy the provided source file or directory to the provided target.
|
|
|
|
* @param source the source file or directory.
|
|
|
|
* @param target the copy destination.
|
|
|
|
* @throws IOException if an IO error occurs.
|
2023-06-25 13:17:46 +02:00
|
|
|
* @throws IllegalStateException if target file already exists and one of source or target is not a directory.
|
2023-06-20 00:15:46 +02:00
|
|
|
* @throws IllegalArgumentException if at least one of the parameter is null, or if the source doesn't exist.
|
2022-07-28 01:13:35 +02:00
|
|
|
*/
|
2021-03-21 20:17:31 +01:00
|
|
|
public static void copy(File source, File target) throws IOException {
|
2023-06-25 13:17:46 +02:00
|
|
|
if (source == null || !source.exists()) {
|
2023-06-20 00:15:46 +02:00
|
|
|
throw new IllegalArgumentException("source is null or doesn't exist: " + source);
|
2022-07-28 01:13:35 +02:00
|
|
|
}
|
|
|
|
if (target == null) {
|
|
|
|
throw new IllegalArgumentException("target cannot be null");
|
|
|
|
}
|
2023-06-25 13:17:46 +02:00
|
|
|
if (target.exists() && !(target.isDirectory() && source.isDirectory())) {
|
|
|
|
throw new IllegalStateException("target file already exists and one of source or target is not a directory: " + target);
|
2021-03-21 20:17:31 +01:00
|
|
|
}
|
2022-07-10 00:55:56 +02:00
|
|
|
BasicFileAttributes sourceAttr = Files.readAttributes(source.toPath(), BasicFileAttributes.class);
|
|
|
|
if (sourceAttr.isDirectory()) {
|
2023-06-25 13:17:46 +02:00
|
|
|
if (!target.exists())
|
|
|
|
target.mkdirs();
|
|
|
|
for (String child : source.list()) {
|
|
|
|
copy(new File(source, child), new File(target, child));
|
2022-07-10 00:55:56 +02:00
|
|
|
}
|
2021-03-21 20:17:31 +01:00
|
|
|
}
|
2022-07-10 00:55:56 +02:00
|
|
|
else if (sourceAttr.isRegularFile()) {
|
2021-03-21 20:17:31 +01:00
|
|
|
Files.copy(source.toPath(), target.toPath());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|