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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. /*
  2. * Copyright (C) 2010, Google Inc.
  3. * Copyright (C) 2010, Matthias Sohn <matthias.sohn@sap.com>
  4. * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com>
  5. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.util;
  46. import java.io.File;
  47. import java.io.IOException;
  48. import java.nio.channels.FileLock;
  49. import java.text.MessageFormat;
  50. import org.eclipse.jgit.internal.JGitText;
  51. /**
  52. * File Utilities
  53. */
  54. public class FileUtils {
  55. /**
  56. * Option to delete given {@code File}
  57. */
  58. public static final int NONE = 0;
  59. /**
  60. * Option to recursively delete given {@code File}
  61. */
  62. public static final int RECURSIVE = 1;
  63. /**
  64. * Option to retry deletion if not successful
  65. */
  66. public static final int RETRY = 2;
  67. /**
  68. * Option to skip deletion if file doesn't exist
  69. */
  70. public static final int SKIP_MISSING = 4;
  71. /**
  72. * Option not to throw exceptions when a deletion finally doesn't succeed.
  73. * @since 2.0
  74. */
  75. public static final int IGNORE_ERRORS = 8;
  76. /**
  77. * Option to only delete empty directories. This option can be combined with
  78. * {@link #RECURSIVE}
  79. *
  80. * @since 2.4
  81. */
  82. public static final int EMPTY_DIRECTORIES_ONLY = 16;
  83. /**
  84. * Delete file or empty folder
  85. *
  86. * @param f
  87. * {@code File} to be deleted
  88. * @throws IOException
  89. * if deletion of {@code f} fails. This may occur if {@code f}
  90. * didn't exist when the method was called. This can therefore
  91. * cause IOExceptions during race conditions when multiple
  92. * concurrent threads all try to delete the same file.
  93. */
  94. public static void delete(final File f) throws IOException {
  95. delete(f, NONE);
  96. }
  97. /**
  98. * Delete file or folder
  99. *
  100. * @param f
  101. * {@code File} to be deleted
  102. * @param options
  103. * deletion options, {@code RECURSIVE} for recursive deletion of
  104. * a subtree, {@code RETRY} to retry when deletion failed.
  105. * Retrying may help if the underlying file system doesn't allow
  106. * deletion of files being read by another thread.
  107. * @throws IOException
  108. * if deletion of {@code f} fails. This may occur if {@code f}
  109. * didn't exist when the method was called. This can therefore
  110. * cause IOExceptions during race conditions when multiple
  111. * concurrent threads all try to delete the same file. This
  112. * exception is not thrown when IGNORE_ERRORS is set.
  113. */
  114. public static void delete(final File f, int options) throws IOException {
  115. if ((options & SKIP_MISSING) != 0 && !f.exists())
  116. return;
  117. if ((options & RECURSIVE) != 0 && f.isDirectory()) {
  118. final File[] items = f.listFiles();
  119. if (items != null) {
  120. for (File c : items)
  121. delete(c, options);
  122. }
  123. }
  124. boolean delete = false;
  125. if ((options & EMPTY_DIRECTORIES_ONLY) != 0) {
  126. if (f.isDirectory()) {
  127. delete = true;
  128. } else {
  129. if ((options & IGNORE_ERRORS) == 0)
  130. throw new IOException(MessageFormat.format(
  131. JGitText.get().deleteFileFailed,
  132. f.getAbsolutePath()));
  133. }
  134. } else {
  135. delete = true;
  136. }
  137. if (delete && !f.delete()) {
  138. if ((options & RETRY) != 0 && f.exists()) {
  139. for (int i = 1; i < 10; i++) {
  140. try {
  141. Thread.sleep(100);
  142. } catch (InterruptedException e) {
  143. // ignore
  144. }
  145. if (f.delete())
  146. return;
  147. }
  148. }
  149. if ((options & IGNORE_ERRORS) == 0)
  150. throw new IOException(MessageFormat.format(
  151. JGitText.get().deleteFileFailed, f.getAbsolutePath()));
  152. }
  153. }
  154. /**
  155. * Rename a file or folder. If the rename fails and if we are running on a
  156. * filesystem where it makes sense to repeat a failing rename then repeat
  157. * the rename operation up to 9 times with 100ms sleep time between two
  158. * calls
  159. *
  160. * @see FS#retryFailedLockFileCommit()
  161. * @param src
  162. * the old {@code File}
  163. * @param dst
  164. * the new {@code File}
  165. * @throws IOException
  166. * if the rename has failed
  167. */
  168. public static void rename(final File src, final File dst)
  169. throws IOException {
  170. int attempts = FS.DETECTED.retryFailedLockFileCommit() ? 10 : 1;
  171. while (--attempts >= 0) {
  172. if (src.renameTo(dst))
  173. return;
  174. try {
  175. Thread.sleep(100);
  176. } catch (InterruptedException e) {
  177. throw new IOException(MessageFormat.format(
  178. JGitText.get().renameFileFailed, src.getAbsolutePath(),
  179. dst.getAbsolutePath()));
  180. }
  181. }
  182. throw new IOException(MessageFormat.format(
  183. JGitText.get().renameFileFailed, src.getAbsolutePath(),
  184. dst.getAbsolutePath()));
  185. }
  186. /**
  187. * Creates the directory named by this abstract pathname.
  188. *
  189. * @param d
  190. * directory to be created
  191. * @throws IOException
  192. * if creation of {@code d} fails. This may occur if {@code d}
  193. * did exist when the method was called. This can therefore
  194. * cause IOExceptions during race conditions when multiple
  195. * concurrent threads all try to create the same directory.
  196. */
  197. public static void mkdir(final File d)
  198. throws IOException {
  199. mkdir(d, false);
  200. }
  201. /**
  202. * Creates the directory named by this abstract pathname.
  203. *
  204. * @param d
  205. * directory to be created
  206. * @param skipExisting
  207. * if {@code true} skip creation of the given directory if it
  208. * already exists in the file system
  209. * @throws IOException
  210. * if creation of {@code d} fails. This may occur if {@code d}
  211. * did exist when the method was called. This can therefore
  212. * cause IOExceptions during race conditions when multiple
  213. * concurrent threads all try to create the same directory.
  214. */
  215. public static void mkdir(final File d, boolean skipExisting)
  216. throws IOException {
  217. if (!d.mkdir()) {
  218. if (skipExisting && d.isDirectory())
  219. return;
  220. throw new IOException(MessageFormat.format(
  221. JGitText.get().mkDirFailed, d.getAbsolutePath()));
  222. }
  223. }
  224. /**
  225. * Creates the directory named by this abstract pathname, including any
  226. * necessary but nonexistent parent directories. Note that if this operation
  227. * fails it may have succeeded in creating some of the necessary parent
  228. * directories.
  229. *
  230. * @param d
  231. * directory to be created
  232. * @throws IOException
  233. * if creation of {@code d} fails. This may occur if {@code d}
  234. * did exist when the method was called. This can therefore
  235. * cause IOExceptions during race conditions when multiple
  236. * concurrent threads all try to create the same directory.
  237. */
  238. public static void mkdirs(final File d) throws IOException {
  239. mkdirs(d, false);
  240. }
  241. /**
  242. * Creates the directory named by this abstract pathname, including any
  243. * necessary but nonexistent parent directories. Note that if this operation
  244. * fails it may have succeeded in creating some of the necessary parent
  245. * directories.
  246. *
  247. * @param d
  248. * directory to be created
  249. * @param skipExisting
  250. * if {@code true} skip creation of the given directory if it
  251. * already exists in the file system
  252. * @throws IOException
  253. * if creation of {@code d} fails. This may occur if {@code d}
  254. * did exist when the method was called. This can therefore
  255. * cause IOExceptions during race conditions when multiple
  256. * concurrent threads all try to create the same directory.
  257. */
  258. public static void mkdirs(final File d, boolean skipExisting)
  259. throws IOException {
  260. if (!d.mkdirs()) {
  261. if (skipExisting && d.isDirectory())
  262. return;
  263. throw new IOException(MessageFormat.format(
  264. JGitText.get().mkDirsFailed, d.getAbsolutePath()));
  265. }
  266. }
  267. /**
  268. * Atomically creates a new, empty file named by this abstract pathname if
  269. * and only if a file with this name does not yet exist. The check for the
  270. * existence of the file and the creation of the file if it does not exist
  271. * are a single operation that is atomic with respect to all other
  272. * filesystem activities that might affect the file.
  273. * <p>
  274. * Note: this method should not be used for file-locking, as the resulting
  275. * protocol cannot be made to work reliably. The {@link FileLock} facility
  276. * should be used instead.
  277. *
  278. * @param f
  279. * the file to be created
  280. * @throws IOException
  281. * if the named file already exists or if an I/O error occurred
  282. */
  283. public static void createNewFile(File f) throws IOException {
  284. if (!f.createNewFile())
  285. throw new IOException(MessageFormat.format(
  286. JGitText.get().createNewFileFailed, f));
  287. }
  288. }