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