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