1 package org.codehaus.plexus.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.nio.file.Files;
22 import java.nio.file.LinkOption;
23 import java.nio.file.Path;
24 import java.nio.file.StandardCopyOption;
25 import java.nio.file.attribute.BasicFileAttributes;
26 import java.nio.file.attribute.PosixFilePermission;
27 import java.util.HashSet;
28 import java.util.Set;
29
30
31
32
33 public class NioFiles {
34 public static boolean isSymbolicLink(File file) {
35 return Files.isSymbolicLink(file.toPath());
36 }
37
38 public static void chmod(File file, int mode) throws IOException {
39 Path path = file.toPath();
40 if (!Files.isSymbolicLink(path)) {
41 Files.setPosixFilePermissions(path, getPermissions(mode));
42 }
43 }
44
45 @SuppressWarnings({"OctalInteger", "MagicNumber"})
46 private static Set<PosixFilePermission> getPermissions(int mode) {
47 Set<PosixFilePermission> perms = new HashSet<>();
48
49 if ((mode & 0400) > 0) {
50 perms.add(PosixFilePermission.OWNER_READ);
51 }
52 if ((mode & 0200) > 0) {
53 perms.add(PosixFilePermission.OWNER_WRITE);
54 }
55 if ((mode & 0100) > 0) {
56 perms.add(PosixFilePermission.OWNER_EXECUTE);
57 }
58
59 if ((mode & 0040) > 0) {
60 perms.add(PosixFilePermission.GROUP_READ);
61 }
62 if ((mode & 0020) > 0) {
63 perms.add(PosixFilePermission.GROUP_WRITE);
64 }
65 if ((mode & 0010) > 0) {
66 perms.add(PosixFilePermission.GROUP_EXECUTE);
67 }
68
69 if ((mode & 0004) > 0) {
70 perms.add(PosixFilePermission.OTHERS_READ);
71 }
72 if ((mode & 0002) > 0) {
73 perms.add(PosixFilePermission.OTHERS_WRITE);
74 }
75 if ((mode & 0001) > 0) {
76 perms.add(PosixFilePermission.OTHERS_EXECUTE);
77 }
78 return perms;
79 }
80
81 public static long getLastModified(File file) throws IOException {
82 BasicFileAttributes basicFileAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
83 return basicFileAttributes.lastModifiedTime().toMillis();
84 }
85
86
87
88
89
90
91
92
93 public static File readSymbolicLink(File symlink) throws IOException {
94 Path path = Files.readSymbolicLink(symlink.toPath());
95 return path.toFile();
96 }
97
98 public static File createSymbolicLink(File symlink, File target) throws IOException {
99 Path link = symlink.toPath();
100 if (Files.exists(link, LinkOption.NOFOLLOW_LINKS)) {
101 Files.delete(link);
102 }
103 link = Files.createSymbolicLink(link, target.toPath());
104 return link.toFile();
105 }
106
107 public static boolean deleteIfExists(File file) throws IOException {
108 return Files.deleteIfExists(file.toPath());
109 }
110
111 public static File copy(File source, File target) throws IOException {
112 Path copy = Files.copy(
113 source.toPath(),
114 target.toPath(),
115 StandardCopyOption.REPLACE_EXISTING,
116 StandardCopyOption.COPY_ATTRIBUTES);
117 return copy.toFile();
118 }
119 }