1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.util;
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.UnsupportedEncodingException;
22 import java.net.MalformedURLException;
23 import java.net.URI;
24 import java.net.URL;
25 import java.net.URLDecoder;
26 import java.nio.charset.StandardCharsets;
27 import java.nio.file.FileSystem;
28 import java.nio.file.FileSystems;
29 import java.nio.file.Path;
30
31 import org.apache.logging.log4j.Logger;
32 import org.apache.logging.log4j.status.StatusLogger;
33
34
35
36
37 public final class FileUtils {
38
39
40 private static final String PROTOCOL_FILE = "file";
41
42 private static final String JBOSS_FILE = "vfsfile";
43
44 private static final Logger LOGGER = StatusLogger.getLogger();
45
46 private FileUtils() {
47 }
48
49
50
51
52
53
54
55 public static File fileFromUri(URI uri) {
56
57 if (uri == null
58 || (uri.getScheme() != null && (!PROTOCOL_FILE.equals(uri.getScheme()) && !JBOSS_FILE.equals(uri
59 .getScheme())))) {
60 return null;
61 }
62 if (uri.getScheme() == null) {
63 File file = new File(uri.toString());
64 if (file.exists()) {
65 return file;
66 }
67 try {
68 final String path = uri.getPath();
69 file = new File(path);
70 if (file.exists()) {
71 return file;
72 }
73 uri = new File(path).toURI();
74 } catch (final Exception ex) {
75 LOGGER.warn("Invalid URI {}", uri);
76 return null;
77 }
78 }
79 final String charsetName = StandardCharsets.UTF_8.name();
80 try {
81 String fileName = uri.toURL().getFile();
82 if (new File(fileName).exists()) {
83 return new File(fileName);
84 }
85 fileName = URLDecoder.decode(fileName, charsetName);
86 return new File(fileName);
87 } catch (final MalformedURLException ex) {
88 LOGGER.warn("Invalid URL {}", uri, ex);
89 } catch (final UnsupportedEncodingException uee) {
90 LOGGER.warn("Invalid encoding: {}", charsetName, uee);
91 }
92 return null;
93 }
94
95 public static boolean isFile(final URL url) {
96 return url != null && (url.getProtocol().equals(PROTOCOL_FILE) || url.getProtocol().equals(JBOSS_FILE));
97 }
98
99 public static String getFileExtension(File file) {
100 String fileName = file.getName();
101 if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
102 return fileName.substring(fileName.lastIndexOf(".") + 1);
103 } else {
104 return null;
105 }
106 }
107
108
109
110
111
112
113
114
115 public static void mkdir(final File dir, final boolean createDirectoryIfNotExisting) throws IOException {
116
117 if (!dir.exists()) {
118 if (!createDirectoryIfNotExisting) {
119 throw new IOException("The directory " + dir.getAbsolutePath() + " does not exist.");
120 }
121 if (!dir.mkdirs()) {
122 throw new IOException("Could not create directory " + dir.getAbsolutePath());
123 }
124 }
125 if (!dir.isDirectory()) {
126 throw new IOException("File " + dir + " exists and is not a directory. Unable to create directory.");
127 }
128 }
129 }