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

FileUtils.java 17 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 2001 The Apache Software Foundation. All rights
  5. * reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in
  16. * the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if
  20. * any, must include the following acknowlegement:
  21. * "This product includes software developed by the
  22. * Apache Software Foundation (http://www.apache.org/)."
  23. * Alternately, this acknowlegement may appear in the software itself,
  24. * if and wherever such third-party acknowlegements normally appear.
  25. *
  26. * 4. The names "The Jakarta Project", "Ant", and "Apache Software
  27. * Foundation" must not be used to endorse or promote products derived
  28. * from this software without prior written permission. For written
  29. * permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache"
  32. * nor may "Apache" appear in their names without prior written
  33. * permission of the Apache Group.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.apache.tools.ant.util;
  55. import java.io.*;
  56. import java.lang.reflect.Method;
  57. import java.util.StringTokenizer;
  58. import java.util.Stack;
  59. import org.apache.tools.ant.BuildException;
  60. import org.apache.tools.ant.Project;
  61. import org.apache.tools.ant.types.FilterSetCollection;
  62. /**
  63. * This class also encapsulates methods which allow Files to be
  64. * refered to using abstract path names which are translated to native
  65. * system file paths at runtime as well as copying files or setting
  66. * there last modification time.
  67. *
  68. * @author duncan@x180.com
  69. * @author <a href="mailto:conor@apache.org">Conor MacNeill</a>
  70. * @author <a href="mailto:stefan.bodewig@epost.de">Stefan Bodewig</a>
  71. */
  72. public class FileUtils {
  73. private static Object lockReflection = new Object();
  74. private static java.lang.reflect.Method setLastModified = null;
  75. /**
  76. * Factory method.
  77. */
  78. public static FileUtils newFileUtils() {
  79. return new FileUtils();
  80. }
  81. /**
  82. * Empty constructor.
  83. */
  84. protected FileUtils() {}
  85. /**
  86. * Convienence method to copy a file from a source to a destination.
  87. * No filtering is performed.
  88. *
  89. * @throws IOException
  90. */
  91. public void copyFile(String sourceFile, String destFile) throws IOException {
  92. copyFile(new File(sourceFile), new File(destFile), null, false, false);
  93. }
  94. /**
  95. * Convienence method to copy a file from a source to a destination
  96. * specifying if token filtering must be used.
  97. *
  98. * @throws IOException
  99. */
  100. public void copyFile(String sourceFile, String destFile, FilterSetCollection filters)
  101. throws IOException
  102. {
  103. copyFile(new File(sourceFile), new File(destFile), filters, false, false);
  104. }
  105. /**
  106. * Convienence method to copy a file from a source to a
  107. * destination specifying if token filtering must be used and if
  108. * source files may overwrite newer destination files.
  109. *
  110. * @throws IOException
  111. */
  112. public void copyFile(String sourceFile, String destFile, FilterSetCollection filters,
  113. boolean overwrite) throws IOException {
  114. copyFile(new File(sourceFile), new File(destFile), filters,
  115. overwrite, false);
  116. }
  117. /**
  118. * Convienence method to copy a file from a source to a
  119. * destination specifying if token filtering must be used, if
  120. * source files may overwrite newer destination files and the
  121. * last modified time of <code>destFile</code> file should be made equal
  122. * to the last modified time of <code>sourceFile</code>.
  123. *
  124. * @throws IOException
  125. */
  126. public void copyFile(String sourceFile, String destFile, FilterSetCollection filters,
  127. boolean overwrite, boolean preserveLastModified)
  128. throws IOException {
  129. copyFile(new File(sourceFile), new File(destFile), filters,
  130. overwrite, preserveLastModified);
  131. }
  132. /**
  133. * Convienence method to copy a file from a source to a destination.
  134. * No filtering is performed.
  135. *
  136. * @throws IOException
  137. */
  138. public void copyFile(File sourceFile, File destFile) throws IOException {
  139. copyFile(sourceFile, destFile, null, false, false);
  140. }
  141. /**
  142. * Convienence method to copy a file from a source to a destination
  143. * specifying if token filtering must be used.
  144. *
  145. * @throws IOException
  146. */
  147. public void copyFile(File sourceFile, File destFile, FilterSetCollection filters)
  148. throws IOException {
  149. copyFile(sourceFile, destFile, filters, false, false);
  150. }
  151. /**
  152. * Convienence method to copy a file from a source to a
  153. * destination specifying if token filtering must be used and if
  154. * source files may overwrite newer destination files.
  155. *
  156. * @throws IOException
  157. */
  158. public void copyFile(File sourceFile, File destFile, FilterSetCollection filters,
  159. boolean overwrite) throws IOException {
  160. copyFile(sourceFile, destFile, filters, overwrite, false);
  161. }
  162. /**
  163. * Convienence method to copy a file from a source to a
  164. * destination specifying if token filtering must be used, if
  165. * source files may overwrite newer destination files and the
  166. * last modified time of <code>destFile</code> file should be made equal
  167. * to the last modified time of <code>sourceFile</code>.
  168. *
  169. * @throws IOException
  170. */
  171. public void copyFile(File sourceFile, File destFile, FilterSetCollection filters,
  172. boolean overwrite, boolean preserveLastModified)
  173. throws IOException {
  174. if (overwrite || !destFile.exists() ||
  175. destFile.lastModified() < sourceFile.lastModified()) {
  176. if (destFile.exists() && destFile.isFile()) {
  177. destFile.delete();
  178. }
  179. // ensure that parent dir of dest file exists!
  180. // not using getParentFile method to stay 1.1 compat
  181. File parent = new File(destFile.getParent());
  182. if (!parent.exists()) {
  183. parent.mkdirs();
  184. }
  185. if (filters != null && filters.hasFilters()) {
  186. BufferedReader in = new BufferedReader(new FileReader(sourceFile));
  187. BufferedWriter out = new BufferedWriter(new FileWriter(destFile));
  188. int length;
  189. String newline = null;
  190. String line = in.readLine();
  191. while (line != null) {
  192. if (line.length() == 0) {
  193. out.newLine();
  194. } else {
  195. newline = filters.replaceTokens(line);
  196. out.write(newline);
  197. out.newLine();
  198. }
  199. line = in.readLine();
  200. }
  201. out.close();
  202. in.close();
  203. } else {
  204. FileInputStream in = new FileInputStream(sourceFile);
  205. FileOutputStream out = new FileOutputStream(destFile);
  206. byte[] buffer = new byte[8 * 1024];
  207. int count = 0;
  208. do {
  209. out.write(buffer, 0, count);
  210. count = in.read(buffer, 0, buffer.length);
  211. } while (count != -1);
  212. in.close();
  213. out.close();
  214. }
  215. if (preserveLastModified) {
  216. setFileLastModified(destFile, sourceFile.lastModified());
  217. }
  218. }
  219. }
  220. /**
  221. * see whether we have a setLastModified method in File and return it.
  222. */
  223. protected final Method getSetLastModified() {
  224. if (Project.getJavaVersion() == Project.JAVA_1_1) {
  225. return null;
  226. }
  227. if (setLastModified == null) {
  228. synchronized (lockReflection) {
  229. if (setLastModified == null) {
  230. try {
  231. setLastModified =
  232. java.io.File.class.getMethod("setLastModified",
  233. new Class[] {Long.TYPE});
  234. } catch (NoSuchMethodException nse) {
  235. throw new BuildException("File.setlastModified not in JDK > 1.1?",
  236. nse);
  237. }
  238. }
  239. }
  240. }
  241. return setLastModified;
  242. }
  243. /**
  244. * Calls File.setLastModified(long time) in a Java 1.1 compatible way.
  245. */
  246. public void setFileLastModified(File file, long time) throws BuildException {
  247. if (Project.getJavaVersion() == Project.JAVA_1_1) {
  248. return;
  249. }
  250. Long[] times = new Long[1];
  251. if (time < 0) {
  252. times[0] = new Long(System.currentTimeMillis());
  253. } else {
  254. times[0] = new Long(time);
  255. }
  256. try {
  257. getSetLastModified().invoke(file, times);
  258. } catch (java.lang.reflect.InvocationTargetException ite) {
  259. Throwable nested = ite.getTargetException();
  260. throw new BuildException("Exception setting the modification time "
  261. + "of " + file, nested);
  262. } catch (Throwable other) {
  263. throw new BuildException("Exception setting the modification time "
  264. + "of " + file, other);
  265. }
  266. }
  267. /**
  268. * Interpret the filename as a file relative to the given file -
  269. * unless the filename already represents an absolute filename.
  270. *
  271. * @param file the "reference" file for relative paths. This
  272. * instance must be an absolute file and must not contain
  273. * &quot;./&quot; or &quot;../&quot; sequences (same for \ instead
  274. * of /). If it is null, this call is equivalent to
  275. * <code>new java.io.File(filename)</code>.
  276. *
  277. * @param filename a file name
  278. *
  279. * @return an absolute file that doesn't contain &quot;./&quot; or
  280. * &quot;../&quot; sequences and uses the correct separator for
  281. * the current platform.
  282. */
  283. public File resolveFile(File file, String filename) {
  284. filename = filename.replace('/', File.separatorChar)
  285. .replace('\\', File.separatorChar);
  286. // deal with absolute files
  287. if (filename.startsWith(File.separator) ||
  288. (filename.length() >= 2 &&
  289. Character.isLetter(filename.charAt(0)) &&
  290. filename.charAt(1) == ':')
  291. ) {
  292. return normalize(filename);
  293. }
  294. if (file == null) {
  295. return new File(filename);
  296. }
  297. File helpFile = new File(file.getAbsolutePath());
  298. StringTokenizer tok = new StringTokenizer(filename, File.separator);
  299. while (tok.hasMoreTokens()) {
  300. String part = tok.nextToken();
  301. if (part.equals("..")) {
  302. String parentFile = helpFile.getParent();
  303. if (parentFile == null) {
  304. String msg = "The file or path you specified ("
  305. + filename + ") is invalid relative to "
  306. + file.getPath();
  307. throw new BuildException(msg);
  308. }
  309. helpFile = new File(parentFile);
  310. } else if (part.equals(".")) {
  311. // Do nothing here
  312. } else {
  313. helpFile = new File(helpFile, part);
  314. }
  315. }
  316. return new File(helpFile.getAbsolutePath());
  317. }
  318. /**
  319. * &quot;normalize&quot; the given absolute path.
  320. *
  321. * <p>This includes:
  322. * <ul>
  323. * <li>Uppercase the drive letter if there is one.</li>
  324. * <li>Remove redundant slashes after the drive spec.</li>
  325. * <li>resolve all ./, .\, ../ and ..\ sequences.</li>
  326. * <li>DOS style paths that start with a drive letter will have
  327. * \ as the separator.</li>
  328. * </ul>
  329. *
  330. * @throws java.lang.NullPointerException if the file path is
  331. * equal to null.
  332. */
  333. public File normalize(String path) {
  334. String orig = path;
  335. path = path.replace('/', File.separatorChar)
  336. .replace('\\', File.separatorChar);
  337. // make sure we are dealing with an absolute path
  338. if (!path.startsWith(File.separator) &&
  339. ! (path.length() >= 2 &&
  340. Character.isLetter(path.charAt(0)) &&
  341. path.charAt(1) == ':')
  342. ) {
  343. String msg = path + " is not an absolute path";
  344. throw new BuildException(msg);
  345. }
  346. boolean dosWithDrive = false;
  347. String root = null;
  348. // Eliminate consecutive slashes after the drive spec
  349. if (path.length() >= 2 &&
  350. Character.isLetter(path.charAt(0)) &&
  351. path.charAt(1) == ':') {
  352. dosWithDrive = true;
  353. char[] ca = path.replace('/', '\\').toCharArray();
  354. StringBuffer sb = new StringBuffer();
  355. sb.append(Character.toUpperCase(ca[0])).append(':');
  356. for (int i = 2; i < ca.length; i++) {
  357. if ((ca[i] != '\\') ||
  358. (ca[i] == '\\' && ca[i - 1] != '\\')
  359. ) {
  360. sb.append(ca[i]);
  361. }
  362. }
  363. path = sb.toString().replace('\\', File.separatorChar);
  364. if (path.length() == 2) {
  365. root = path;
  366. path = "";
  367. } else {
  368. root = path.substring(0, 3);
  369. path = path.substring(3);
  370. }
  371. } else {
  372. if (path.length() == 1) {
  373. root = File.separator;
  374. path = "";
  375. } else if (path.charAt(1) == File.separatorChar) {
  376. // UNC drive
  377. root = File.separator+File.separator;
  378. path = path.substring(2);
  379. } else {
  380. root = File.separator;
  381. path = path.substring(1);
  382. }
  383. }
  384. Stack s = new Stack();
  385. s.push(root);
  386. StringTokenizer tok = new StringTokenizer(path, File.separator);
  387. while (tok.hasMoreTokens()) {
  388. String thisToken = tok.nextToken();
  389. if (".".equals(thisToken)) {
  390. continue;
  391. } else if ("..".equals(thisToken)) {
  392. if (s.size() < 2) {
  393. throw new BuildException("Cannot resolve path "+orig);
  394. } else {
  395. s.pop();
  396. }
  397. } else { // plain component
  398. s.push(thisToken);
  399. }
  400. }
  401. StringBuffer sb = new StringBuffer();
  402. for (int i=0; i<s.size(); i++) {
  403. if (i > 1) {
  404. // not before the filesystem root and not after it, since root
  405. // already contains one
  406. sb.append(File.separatorChar);
  407. }
  408. sb.append(s.elementAt(i));
  409. }
  410. path = sb.toString();
  411. if (dosWithDrive) {
  412. path = path.replace('/', '\\');
  413. }
  414. return new File(path);
  415. }
  416. }