]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.util/src/org/argeo/util/FsUtils.java
Start release cycle
[lgpl/argeo-commons.git] / org.argeo.util / src / org / argeo / util / FsUtils.java
1 package org.argeo.util;
2
3 import java.io.IOException;
4 import java.nio.file.FileVisitResult;
5 import java.nio.file.Files;
6 import java.nio.file.Path;
7 import java.nio.file.SimpleFileVisitor;
8 import java.nio.file.attribute.BasicFileAttributes;
9
10 /** Utilities around the standard Java file abstractions. */
11 public class FsUtils {
12
13 /**
14 * Deletes this path, recursively if needed. Does nothing if the path does not
15 * exist.
16 */
17 public static void copyDirectory(Path source, Path target) {
18 if (!Files.exists(source) || !Files.isDirectory(source))
19 throw new IllegalArgumentException(source + " is not a directory");
20 if (Files.exists(target) && !Files.isDirectory(target))
21 throw new IllegalArgumentException(target + " is not a directory");
22 try {
23 Files.createDirectories(target);
24 Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
25 @Override
26 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
27 if (e != null)
28 throw e;
29 Path relativePath = source.relativize(directory);
30 Path targetDirectory = target.resolve(relativePath);
31 Files.createDirectory(targetDirectory);
32 return FileVisitResult.CONTINUE;
33 }
34
35 @Override
36 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
37 Path relativePath = source.relativize(file);
38 Path targetFile = target.resolve(relativePath);
39 Files.copy(file, targetFile);
40 return FileVisitResult.CONTINUE;
41 }
42 });
43 } catch (IOException e) {
44 throw new RuntimeException("Cannot copy " + source + " to " + target, e);
45 }
46
47 }
48
49 /**
50 * Deletes this path, recursively if needed. Does nothing if the path does not
51 * exist.
52 */
53 public static void delete(Path path) {
54 try {
55 if (!Files.exists(path))
56 return;
57 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
58 @Override
59 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
60 if (e != null)
61 throw e;
62 Files.delete(directory);
63 return FileVisitResult.CONTINUE;
64 }
65
66 @Override
67 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
68 Files.delete(file);
69 return FileVisitResult.CONTINUE;
70 }
71 });
72 } catch (IOException e) {
73 throw new RuntimeException("Cannot delete " + path, e);
74 }
75 }
76
77 /** Singleton. */
78 private FsUtils() {
79 }
80
81 }