1 package org
.argeo
.util
;
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
;
10 /** Utilities around the standard Java file abstractions. */
11 public class FsUtils
{
14 * Deletes this path, recursively if needed. Does nothing if the path does not
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");
23 Files
.createDirectories(target
);
24 Files
.walkFileTree(source
, new SimpleFileVisitor
<Path
>() {
26 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
29 Path relativePath
= source
.relativize(directory
);
30 Path targetDirectory
= target
.resolve(relativePath
);
31 Files
.createDirectory(targetDirectory
);
32 return FileVisitResult
.CONTINUE
;
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
;
43 } catch (IOException e
) {
44 throw new RuntimeException("Cannot copy " + source
+ " to " + target
, e
);
50 * Deletes this path, recursively if needed. Does nothing if the path does not
53 public static void delete(Path path
) {
55 if (!Files
.exists(path
))
57 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
59 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
62 Files
.delete(directory
);
63 return FileVisitResult
.CONTINUE
;
67 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
69 return FileVisitResult
.CONTINUE
;
72 } catch (IOException e
) {
73 throw new RuntimeException("Cannot delete " + path
, e
);