You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileUtils.java 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /*
  2. * Copyright (c) 2006-2015 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.util.io;
  23. import java.io.IOException;
  24. import java.net.URI;
  25. import java.net.URISyntaxException;
  26. import java.net.URL;
  27. import java.nio.file.CopyOption;
  28. import java.nio.file.DirectoryStream;
  29. import java.nio.file.FileSystem;
  30. import java.nio.file.FileSystems;
  31. import java.nio.file.Files;
  32. import java.nio.file.Path;
  33. import java.nio.file.Paths;
  34. import java.nio.file.StandardCopyOption;
  35. import java.security.CodeSource;
  36. import java.security.ProtectionDomain;
  37. import java.util.HashMap;
  38. import java.util.Map;
  39. import java.util.Optional;
  40. /**
  41. * Utility class to deal with files.
  42. */
  43. public final class FileUtils {
  44. private static final Optional<FileSystem> JAR_FILE_SYSTEM = getJarFileSystem();
  45. private FileUtils() {
  46. // Shouldn't be instansiated.
  47. }
  48. private static Optional<FileSystem> getJarFileSystem() {
  49. if (isRunningFromJar(FileUtils.class)) {
  50. try {
  51. final FileSystem fs = FileSystems.newFileSystem(
  52. getApplicationPath(FileUtils.class), null);
  53. return Optional.of(fs);
  54. } catch (IOException ex) {
  55. return Optional.empty();
  56. }
  57. } else {
  58. return Optional.empty();
  59. }
  60. }
  61. /**
  62. * Checks whether this application has been run from a jar or not.
  63. *
  64. * @param clazz Class used to locate the application
  65. *
  66. * @return true if the application was launched from a jar, false otherwise
  67. *
  68. * @throws IllegalStateException If the application path cannot be determined for any reason
  69. */
  70. public static boolean isRunningFromJar(final Class<?> clazz) throws IllegalStateException {
  71. return getApplicationPath(clazz).getFileName().toString().endsWith(".jar");
  72. }
  73. /**
  74. * Returns the base location for the specified class, this is either the a jar or a folder
  75. * depending on how the application was launched.
  76. *
  77. * This can fail for a number of reasons, it is not wholly reliable.
  78. *
  79. * @param clazz Class used to locate the application
  80. *
  81. * @return A {@link Path} to application location
  82. *
  83. * @throws IllegalStateException If the application path cannot be determined for any reason
  84. */
  85. public static Path getApplicationPath(final Class<?> clazz) throws IllegalStateException {
  86. final ProtectionDomain pd;
  87. try {
  88. pd = clazz.getProtectionDomain();
  89. } catch (SecurityException ex) {
  90. throw new IllegalStateException("Unable to get protection domain", ex);
  91. }
  92. final CodeSource cs = pd.getCodeSource();
  93. if (cs == null) {
  94. throw new IllegalStateException("Unable to get the code source");
  95. }
  96. final URI uri;
  97. try {
  98. uri = cs.getLocation().toURI();
  99. } catch (URISyntaxException ex) {
  100. throw new IllegalStateException("Unable to convert location to URI", ex);
  101. }
  102. return Paths.get(uri);
  103. }
  104. /**
  105. * Recursively copies the resources specified by the given URL to the destination folder.
  106. * Existing files will be replaced.
  107. *
  108. * @param source The resource to be copied (file or folder).
  109. * @param destination The destination folder to copy the resource to.
  110. * @throws IOException If the resource couldn't be copied.
  111. */
  112. public static void copyResourcesContents(final URL source, final Path destination)
  113. throws IOException {
  114. doCopyResources(source, destination, true);
  115. }
  116. /**
  117. * Recursively copies the resources specified by the given URL to the destination folder.
  118. * Existing files will be replaced.
  119. *
  120. * @param source The resource to be copied (file or folder).
  121. * @param destination The destination folder to copy the resource to.
  122. * @throws IOException If the resource couldn't be copied.
  123. */
  124. public static void copyResources(final URL source, final Path destination) throws IOException {
  125. doCopyResources(source, destination, false);
  126. }
  127. private static void doCopyResources(final URL source, final Path destination,
  128. final boolean contents) throws IOException {
  129. try {
  130. final String path = source.toURI().toString();
  131. final int index = path.indexOf("!/");
  132. if (index > -1) {
  133. final String file = path.substring(0, index);
  134. final Map<String, String> env = new HashMap<>();
  135. try (final FileSystem fs = FileSystems.newFileSystem(URI.create(file), env)) {
  136. doCopyRecursively(fs.getPath(path.substring(index + 2)), destination, contents,
  137. StandardCopyOption.REPLACE_EXISTING);
  138. }
  139. } else {
  140. doCopyRecursively(Paths.get(source.toURI()), destination, contents,
  141. StandardCopyOption.REPLACE_EXISTING);
  142. }
  143. } catch (URISyntaxException ex) {
  144. throw new IOException("Unable to get source URI", ex);
  145. }
  146. }
  147. /**
  148. * Returns a {@link Path} for the specified bundled resource. If the app is running from a jar,
  149. * the resource will be backed by a Zip file system.
  150. *
  151. * @param resource The resource to get a path for
  152. * @return The path for the specified resource
  153. * @throws URISyntaxException If the resource could not be mapped to a path
  154. */
  155. public static Path getPathForResource(final URL resource) throws URISyntaxException {
  156. if (JAR_FILE_SYSTEM.isPresent()) {
  157. final String path = resource.toURI().toString();
  158. final int index = path.indexOf("!/");
  159. if (index > -1) {
  160. return JAR_FILE_SYSTEM.get().getPath(path.substring(index + 1));
  161. }
  162. }
  163. return Paths.get(resource.toURI());
  164. }
  165. /**
  166. * Recursively copies the contents of one path to another. Once complete, a deep copy of the
  167. * source file or folder will be present in the destination directory.
  168. *
  169. * @param source The path that should be copied.
  170. * @param destination The directory to place copied files in.
  171. * @param options Options to use when copying.
  172. * @throws IOException If any files couldn't be copied.
  173. */
  174. public static void copyRecursivelyContents(final Path source, final Path destination,
  175. final CopyOption... options) throws IOException {
  176. doCopyRecursively(source, destination, true, options);
  177. }
  178. /**
  179. * Recursively copies one path to another. Once complete, a deep copy of the source file or
  180. * folder will be present in the destination directory.
  181. *
  182. * @param source The path that should be copied.
  183. * @param destination The directory to place copied files in.
  184. * @param options Options to use when copying.
  185. * @throws IOException If any files couldn't be copied.
  186. */
  187. public static void copyRecursively(final Path source, final Path destination,
  188. final CopyOption... options) throws IOException {
  189. doCopyRecursively(source, destination, false, options);
  190. }
  191. private static void doCopyRecursively(final Path source, final Path destination,
  192. final boolean contents, final CopyOption... options) throws IOException {
  193. final Path destinationPath;
  194. if (contents) {
  195. destinationPath = destination;
  196. } else {
  197. destinationPath = destination.resolve(source.getFileName().toString());
  198. }
  199. if (Files.isDirectory(source)) {
  200. Files.createDirectories(destinationPath);
  201. try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(source)) {
  202. for (Path path : directoryStream) {
  203. copyRecursively(path, destinationPath, options);
  204. }
  205. }
  206. } else {
  207. Files.copy(source, destinationPath, options);
  208. }
  209. }
  210. }