]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/util/FsUtils.java
Simplify and document new content provider implementation
[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) throws IOException {
51 if (!Files.exists(path))
52 return;
53 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
54 @Override
55 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
56 if (e != null)
57 throw e;
58 Files.delete(directory);
59 return FileVisitResult.CONTINUE;
60 }
61
62 @Override
63 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
64 Files.delete(file);
65 return FileVisitResult.CONTINUE;
66 }
67 });
68 }
69
70 /** Singleton. */
71 private FsUtils() {
72 }
73
74 }