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 64 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  1. /*
  2. * Copyright 2001-2005 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package org.apache.tools.ant.util;
  18. import java.io.BufferedInputStream;
  19. import java.io.BufferedReader;
  20. import java.io.BufferedWriter;
  21. import java.io.File;
  22. import java.io.FileInputStream;
  23. import java.io.FileOutputStream;
  24. import java.io.FileReader;
  25. import java.io.FileWriter;
  26. import java.io.IOException;
  27. import java.io.InputStream;
  28. import java.io.InputStreamReader;
  29. import java.io.OutputStreamWriter;
  30. import java.io.Reader;
  31. import java.io.Writer;
  32. import java.io.OutputStream;
  33. import java.net.MalformedURLException;
  34. import java.net.URL;
  35. import java.text.CharacterIterator;
  36. import java.text.DecimalFormat;
  37. import java.text.StringCharacterIterator;
  38. import java.util.Random;
  39. import java.util.Stack;
  40. import java.util.StringTokenizer;
  41. import java.util.Vector;
  42. import org.apache.tools.ant.BuildException;
  43. import org.apache.tools.ant.Project;
  44. import org.apache.tools.ant.filters.util.ChainReaderHelper;
  45. import org.apache.tools.ant.taskdefs.condition.Os;
  46. import org.apache.tools.ant.types.Resource;
  47. import org.apache.tools.ant.types.FilterSetCollection;
  48. import org.apache.tools.ant.types.resources.Touchable;
  49. import org.apache.tools.ant.types.resources.FileResource;
  50. import org.apache.tools.ant.launch.Locator;
  51. /**
  52. * This class also encapsulates methods which allow Files to be
  53. * referred to using abstract path names which are translated to native
  54. * system file paths at runtime as well as copying files or setting
  55. * their last modification time.
  56. *
  57. */
  58. public class FileUtils {
  59. private static final FileUtils PRIMARY_INSTANCE = new FileUtils();
  60. //get some non-crypto-grade randomness from various places.
  61. private static Random rand = new Random(System.currentTimeMillis()
  62. + Runtime.getRuntime().freeMemory());
  63. private static boolean onNetWare = Os.isFamily("netware");
  64. private static boolean onDos = Os.isFamily("dos");
  65. private static boolean onWin9x = Os.isFamily("win9x");
  66. private static boolean onWindows = Os.isFamily("windows");
  67. private static final int BUF_SIZE = 8192;
  68. // for toURI
  69. private static boolean[] isSpecial = new boolean[256];
  70. private static char[] escapedChar1 = new char[256];
  71. private static char[] escapedChar2 = new char[256];
  72. /**
  73. * The granularity of timestamps under FAT.
  74. */
  75. public static final long FAT_FILE_TIMESTAMP_GRANULARITY = 2000;
  76. /**
  77. * The granularity of timestamps under Unix.
  78. */
  79. public static final long UNIX_FILE_TIMESTAMP_GRANULARITY = 1000;
  80. /**
  81. * The granularity of timestamps under the NT File System.
  82. * NTFS has a granularity of 100 nanoseconds, which is less
  83. * than 1 millisecond, so we round this up to 1 millisecond.
  84. */
  85. public static final long NTFS_FILE_TIMESTAMP_GRANULARITY = 1;
  86. // stolen from FilePathToURI of the Xerces-J team
  87. static {
  88. for (int i = 0; i <= 0x20; i++) {
  89. isSpecial[i] = true;
  90. escapedChar1[i] = Character.forDigit(i >> 4, 16);
  91. escapedChar2[i] = Character.forDigit(i & 0xf, 16);
  92. }
  93. isSpecial[0x7f] = true;
  94. escapedChar1[0x7f] = '7';
  95. escapedChar2[0x7f] = 'F';
  96. char[] escChs = {'<', '>', '#', '%', '"', '{', '}',
  97. '|', '\\', '^', '~', '[', ']', '`'};
  98. int len = escChs.length;
  99. char ch;
  100. for (int i = 0; i < len; i++) {
  101. ch = escChs[i];
  102. isSpecial[ch] = true;
  103. escapedChar1[ch] = Character.forDigit(ch >> 4, 16);
  104. escapedChar2[ch] = Character.forDigit(ch & 0xf, 16);
  105. }
  106. }
  107. /**
  108. * Factory method.
  109. *
  110. * @return a new instance of FileUtils.
  111. * @deprecated Use getFileUtils instead, FileUtils do not have state.
  112. */
  113. public static FileUtils newFileUtils() {
  114. return new FileUtils();
  115. }
  116. /**
  117. * Method to retrieve The FileUtils, which is shared by all users of this
  118. * method.
  119. * @return an instance of FileUtils.
  120. * @since Ant 1.6.3
  121. */
  122. public static FileUtils getFileUtils() {
  123. return PRIMARY_INSTANCE;
  124. }
  125. /**
  126. * Empty constructor.
  127. */
  128. protected FileUtils() {
  129. }
  130. /**
  131. * Get the URL for a file taking into account # characters.
  132. *
  133. * @param file the file whose URL representation is required.
  134. * @return The FileURL value.
  135. * @throws MalformedURLException if the URL representation cannot be
  136. * formed.
  137. */
  138. public URL getFileURL(File file) throws MalformedURLException {
  139. return new URL(toURI(file.getAbsolutePath()));
  140. }
  141. /**
  142. * Convenience method to copy a file from a source to a destination.
  143. * No filtering is performed.
  144. *
  145. * @param sourceFile Name of file to copy from.
  146. * Must not be <code>null</code>.
  147. * @param destFile Name of file to copy to.
  148. * Must not be <code>null</code>.
  149. *
  150. * @throws IOException if the copying fails.
  151. */
  152. public void copyFile(String sourceFile, String destFile)
  153. throws IOException {
  154. copyFile(new File(sourceFile), new File(destFile), null, false, false);
  155. }
  156. /**
  157. * Convenience method to copy a file from a source to a destination
  158. * specifying if token filtering must be used.
  159. *
  160. * @param sourceFile Name of file to copy from.
  161. * Must not be <code>null</code>.
  162. * @param destFile Name of file to copy to.
  163. * Must not be <code>null</code>.
  164. * @param filters the collection of filters to apply to this copy.
  165. *
  166. * @throws IOException if the copying fails.
  167. */
  168. public void copyFile(String sourceFile, String destFile,
  169. FilterSetCollection filters)
  170. throws IOException {
  171. copyFile(new File(sourceFile), new File(destFile), filters,
  172. false, false);
  173. }
  174. /**
  175. * Convenience method to copy a file from a source to a
  176. * destination specifying if token filtering must be used and if
  177. * source files may overwrite newer destination files.
  178. *
  179. * @param sourceFile Name of file to copy from.
  180. * Must not be <code>null</code>.
  181. * @param destFile Name of file to copy to.
  182. * Must not be <code>null</code>.
  183. * @param filters the collection of filters to apply to this copy.
  184. * @param overwrite Whether or not the destination file should be
  185. * overwritten if it already exists.
  186. *
  187. * @throws IOException if the copying fails.
  188. */
  189. public void copyFile(String sourceFile, String destFile, FilterSetCollection filters,
  190. boolean overwrite) throws IOException {
  191. copyFile(new File(sourceFile), new File(destFile), filters,
  192. overwrite, false);
  193. }
  194. /**
  195. * Convenience method to copy a file from a source to a
  196. * destination specifying if token filtering must be used, if
  197. * source files may overwrite newer destination files and the
  198. * last modified time of <code>destFile</code> file should be made equal
  199. * to the last modified time of <code>sourceFile</code>.
  200. *
  201. * @param sourceFile Name of file to copy from.
  202. * Must not be <code>null</code>.
  203. * @param destFile Name of file to copy to.
  204. * Must not be <code>null</code>.
  205. * @param filters the collection of filters to apply to this copy.
  206. * @param overwrite Whether or not the destination file should be
  207. * overwritten if it already exists.
  208. * @param preserveLastModified Whether or not the last modified time of
  209. * the resulting file should be set to that
  210. * of the source file.
  211. *
  212. * @throws IOException if the copying fails.
  213. */
  214. public void copyFile(String sourceFile, String destFile, FilterSetCollection filters,
  215. boolean overwrite, boolean preserveLastModified)
  216. throws IOException {
  217. copyFile(new File(sourceFile), new File(destFile), filters,
  218. overwrite, preserveLastModified);
  219. }
  220. /**
  221. * Convenience method to copy a file from a source to a
  222. * destination specifying if token filtering must be used, if
  223. * source files may overwrite newer destination files and the
  224. * last modified time of <code>destFile</code> file should be made equal
  225. * to the last modified time of <code>sourceFile</code>.
  226. *
  227. * @param sourceFile Name of file to copy from.
  228. * Must not be <code>null</code>.
  229. * @param destFile Name of file to copy to.
  230. * Must not be <code>null</code>.
  231. * @param filters the collection of filters to apply to this copy.
  232. * @param overwrite Whether or not the destination file should be
  233. * overwritten if it already exists.
  234. * @param preserveLastModified Whether or not the last modified time of
  235. * the resulting file should be set to that
  236. * of the source file.
  237. * @param encoding the encoding used to read and write the files.
  238. *
  239. * @throws IOException if the copying fails.
  240. *
  241. * @since Ant 1.5
  242. */
  243. public void copyFile(String sourceFile, String destFile,
  244. FilterSetCollection filters, boolean overwrite,
  245. boolean preserveLastModified, String encoding)
  246. throws IOException {
  247. copyFile(new File(sourceFile), new File(destFile), filters,
  248. overwrite, preserveLastModified, encoding);
  249. }
  250. /**
  251. * Convenience method to copy a file from a source to a
  252. * destination specifying if token filtering must be used, if
  253. * filter chains must be used, if source files may overwrite
  254. * newer destination files and the last modified time of
  255. * <code>destFile</code> file should be made equal
  256. * to the last modified time of <code>sourceFile</code>.
  257. *
  258. * @param sourceFile Name of file to copy from.
  259. * Must not be <code>null</code>.
  260. * @param destFile Name of file to copy to.
  261. * Must not be <code>null</code>.
  262. * @param filters the collection of filters to apply to this copy.
  263. * @param filterChains filterChains to apply during the copy.
  264. * @param overwrite Whether or not the destination file should be
  265. * overwritten if it already exists.
  266. * @param preserveLastModified Whether or not the last modified time of
  267. * the resulting file should be set to that
  268. * of the source file.
  269. * @param encoding the encoding used to read and write the files.
  270. * @param project the project instance.
  271. *
  272. * @throws IOException if the copying fails.
  273. *
  274. * @since Ant 1.5
  275. */
  276. public void copyFile(String sourceFile, String destFile,
  277. FilterSetCollection filters, Vector filterChains,
  278. boolean overwrite, boolean preserveLastModified,
  279. String encoding, Project project)
  280. throws IOException {
  281. copyFile(new File(sourceFile), new File(destFile), filters,
  282. filterChains, overwrite, preserveLastModified,
  283. encoding, project);
  284. }
  285. /**
  286. * Convenience method to copy a file from a source to a
  287. * destination specifying if token filtering must be used, if
  288. * filter chains must be used, if source files may overwrite
  289. * newer destination files and the last modified time of
  290. * <code>destFile</code> file should be made equal
  291. * to the last modified time of <code>sourceFile</code>.
  292. *
  293. * @param sourceFile Name of file to copy from.
  294. * Must not be <code>null</code>.
  295. * @param destFile Name of file to copy to.
  296. * Must not be <code>null</code>.
  297. * @param filters the collection of filters to apply to this copy.
  298. * @param filterChains filterChains to apply during the copy.
  299. * @param overwrite Whether or not the destination file should be
  300. * overwritten if it already exists.
  301. * @param preserveLastModified Whether or not the last modified time of
  302. * the resulting file should be set to that
  303. * of the source file.
  304. * @param inputEncoding the encoding used to read the files.
  305. * @param outputEncoding the encoding used to write the files.
  306. * @param project the project instance.
  307. *
  308. * @throws IOException if the copying fails.
  309. *
  310. * @since Ant 1.6
  311. */
  312. public void copyFile(String sourceFile, String destFile,
  313. FilterSetCollection filters, Vector filterChains,
  314. boolean overwrite, boolean preserveLastModified,
  315. String inputEncoding, String outputEncoding,
  316. Project project)
  317. throws IOException {
  318. copyFile(new File(sourceFile), new File(destFile), filters,
  319. filterChains, overwrite, preserveLastModified,
  320. inputEncoding, outputEncoding, project);
  321. }
  322. /**
  323. * Convenience method to copy a file from a source to a destination.
  324. * No filtering is performed.
  325. *
  326. * @param sourceFile the file to copy from.
  327. * Must not be <code>null</code>.
  328. * @param destFile the file to copy to.
  329. * Must not be <code>null</code>.
  330. *
  331. * @throws IOException if the copying fails.
  332. */
  333. public void copyFile(File sourceFile, File destFile) throws IOException {
  334. copyFile(sourceFile, destFile, null, false, false);
  335. }
  336. /**
  337. * Convenience method to copy a file from a source to a destination
  338. * specifying if token filtering must be used.
  339. *
  340. * @param sourceFile the file to copy from.
  341. * Must not be <code>null</code>.
  342. * @param destFile the file to copy to.
  343. * Must not be <code>null</code>.
  344. * @param filters the collection of filters to apply to this copy.
  345. *
  346. * @throws IOException if the copying fails.
  347. */
  348. public void copyFile(File sourceFile, File destFile, FilterSetCollection filters)
  349. throws IOException {
  350. copyFile(sourceFile, destFile, filters, false, false);
  351. }
  352. /**
  353. * Convenience method to copy a file from a source to a
  354. * destination specifying if token filtering must be used and if
  355. * source files may overwrite newer destination files.
  356. *
  357. * @param sourceFile the file to copy from.
  358. * Must not be <code>null</code>.
  359. * @param destFile the file to copy to.
  360. * Must not be <code>null</code>.
  361. * @param filters the collection of filters to apply to this copy.
  362. * @param overwrite Whether or not the destination file should be
  363. * overwritten if it already exists.
  364. *
  365. * @throws IOException if the copying fails.
  366. */
  367. public void copyFile(File sourceFile, File destFile, FilterSetCollection filters,
  368. boolean overwrite) throws IOException {
  369. copyFile(sourceFile, destFile, filters, overwrite, false);
  370. }
  371. /**
  372. * Convenience method to copy a file from a source to a
  373. * destination specifying if token filtering must be used, if
  374. * source files may overwrite newer destination files and the
  375. * last modified time of <code>destFile</code> file should be made equal
  376. * to the last modified time of <code>sourceFile</code>.
  377. *
  378. * @param sourceFile the file to copy from.
  379. * Must not be <code>null</code>.
  380. * @param destFile the file to copy to.
  381. * Must not be <code>null</code>.
  382. * @param filters the collection of filters to apply to this copy.
  383. * @param overwrite Whether or not the destination file should be
  384. * overwritten if it already exists.
  385. * @param preserveLastModified Whether or not the last modified time of
  386. * the resulting file should be set to that
  387. * of the source file.
  388. *
  389. * @throws IOException if the copying fails.
  390. */
  391. public void copyFile(File sourceFile, File destFile, FilterSetCollection filters,
  392. boolean overwrite, boolean preserveLastModified)
  393. throws IOException {
  394. copyFile(sourceFile, destFile, filters, overwrite,
  395. preserveLastModified, null);
  396. }
  397. /**
  398. * Convenience method to copy a file from a source to a
  399. * destination specifying if token filtering must be used, if
  400. * source files may overwrite newer destination files, the last
  401. * modified time of <code>destFile</code> file should be made
  402. * equal to the last modified time of <code>sourceFile</code> and
  403. * which character encoding to assume.
  404. *
  405. * @param sourceFile the file to copy from.
  406. * Must not be <code>null</code>.
  407. * @param destFile the file to copy to.
  408. * Must not be <code>null</code>.
  409. * @param filters the collection of filters to apply to this copy.
  410. * @param overwrite Whether or not the destination file should be
  411. * overwritten if it already exists.
  412. * @param preserveLastModified Whether or not the last modified time of
  413. * the resulting file should be set to that
  414. * of the source file.
  415. * @param encoding the encoding used to read and write the files.
  416. *
  417. * @throws IOException if the copying fails.
  418. *
  419. * @since Ant 1.5
  420. */
  421. public void copyFile(File sourceFile, File destFile,
  422. FilterSetCollection filters, boolean overwrite,
  423. boolean preserveLastModified, String encoding)
  424. throws IOException {
  425. copyFile(sourceFile, destFile, filters, null, overwrite,
  426. preserveLastModified, encoding, null);
  427. }
  428. /**
  429. * Convenience method to copy a file from a source to a
  430. * destination specifying if token filtering must be used, if
  431. * filter chains must be used, if source files may overwrite
  432. * newer destination files and the last modified time of
  433. * <code>destFile</code> file should be made equal
  434. * to the last modified time of <code>sourceFile</code>.
  435. *
  436. * @param sourceFile the file to copy from.
  437. * Must not be <code>null</code>.
  438. * @param destFile the file to copy to.
  439. * Must not be <code>null</code>.
  440. * @param filters the collection of filters to apply to this copy.
  441. * @param filterChains filterChains to apply during the copy.
  442. * @param overwrite Whether or not the destination file should be
  443. * overwritten if it already exists.
  444. * @param preserveLastModified Whether or not the last modified time of
  445. * the resulting file should be set to that
  446. * of the source file.
  447. * @param encoding the encoding used to read and write the files.
  448. * @param project the project instance.
  449. *
  450. * @throws IOException if the copying fails.
  451. *
  452. * @since Ant 1.5
  453. */
  454. public void copyFile(File sourceFile, File destFile,
  455. FilterSetCollection filters, Vector filterChains,
  456. boolean overwrite, boolean preserveLastModified,
  457. String encoding, Project project)
  458. throws IOException {
  459. copyFile(sourceFile, destFile, filters, filterChains,
  460. overwrite, preserveLastModified, encoding, encoding, project);
  461. }
  462. /**
  463. * Convenience method to copy a file from a source to a
  464. * destination specifying if token filtering must be used, if
  465. * filter chains must be used, if source files may overwrite
  466. * newer destination files and the last modified time of
  467. * <code>destFile</code> file should be made equal
  468. * to the last modified time of <code>sourceFile</code>.
  469. *
  470. * @param sourceFile the file to copy from.
  471. * Must not be <code>null</code>.
  472. * @param destFile the file to copy to.
  473. * Must not be <code>null</code>.
  474. * @param filters the collection of filters to apply to this copy.
  475. * @param filterChains filterChains to apply during the copy.
  476. * @param overwrite Whether or not the destination file should be
  477. * overwritten if it already exists.
  478. * @param preserveLastModified Whether or not the last modified time of
  479. * the resulting file should be set to that
  480. * of the source file.
  481. * @param inputEncoding the encoding used to read the files.
  482. * @param outputEncoding the encoding used to write the files.
  483. * @param project the project instance.
  484. *
  485. *
  486. * @throws IOException if the copying fails.
  487. *
  488. * @since Ant 1.6
  489. */
  490. public void copyFile(File sourceFile, File destFile,
  491. FilterSetCollection filters, Vector filterChains,
  492. boolean overwrite, boolean preserveLastModified,
  493. String inputEncoding, String outputEncoding,
  494. Project project)
  495. throws IOException {
  496. copyResource(new FileResource(sourceFile), new FileResource(destFile),
  497. filters, filterChains, overwrite, preserveLastModified,
  498. inputEncoding, outputEncoding, project);
  499. }
  500. /**
  501. * Convenience method to copy content from one Resource to another.
  502. * No filtering is performed.
  503. *
  504. * @param source the Resource to copy from.
  505. * Must not be <code>null</code>.
  506. * @param dest the Resource to copy to.
  507. * Must not be <code>null</code>.
  508. *
  509. * @throws IOException if the copying fails.
  510. *
  511. * @since Ant 1.7
  512. */
  513. public void copyResource(Resource source, Resource dest) throws IOException {
  514. copyResource(source, dest, null);
  515. }
  516. /**
  517. * Convenience method to copy content from one Resource to another.
  518. * No filtering is performed.
  519. *
  520. * @param source the Resource to copy from.
  521. * Must not be <code>null</code>.
  522. * @param dest the Resource to copy to.
  523. * Must not be <code>null</code>.
  524. * @param project the project instance.
  525. *
  526. * @throws IOException if the copying fails.
  527. *
  528. * @since Ant 1.7
  529. */
  530. public void copyResource(Resource source, Resource dest, Project project)
  531. throws IOException {
  532. copyResource(source, dest, null, null, false,
  533. false, null, null, project);
  534. }
  535. /**
  536. * Convenience method to copy content from one Resource to another
  537. * specifying whether token filtering must be used, whether filter chains
  538. * must be used, whether newer destination files may be overwritten and
  539. * whether the last modified time of <code>dest</code> file should be made
  540. * equal to the last modified time of <code>source</code>.
  541. *
  542. * @param source the Resource to copy from.
  543. * Must not be <code>null</code>.
  544. * @param dest the Resource to copy to.
  545. * Must not be <code>null</code>.
  546. * @param filters the collection of filters to apply to this copy.
  547. * @param filterChains filterChains to apply during the copy.
  548. * @param overwrite Whether or not the destination Resource should be
  549. * overwritten if it already exists.
  550. * @param preserveLastModified Whether or not the last modified time of
  551. * the destination Resource should be set to that
  552. * of the source.
  553. * @param inputEncoding the encoding used to read the files.
  554. * @param outputEncoding the encoding used to write the files.
  555. * @param project the project instance.
  556. *
  557. * @throws IOException if the copying fails.
  558. *
  559. * @since Ant 1.7
  560. */
  561. public void copyResource(Resource source, Resource dest,
  562. FilterSetCollection filters, Vector filterChains,
  563. boolean overwrite, boolean preserveLastModified,
  564. String inputEncoding, String outputEncoding,
  565. Project project)
  566. throws IOException {
  567. if (!overwrite) {
  568. long slm = source.getLastModified();
  569. if (dest.isExists() && slm != 0
  570. && dest.getLastModified() > slm) {
  571. return;
  572. }
  573. }
  574. final boolean filterSetsAvailable = (filters != null
  575. && filters.hasFilters());
  576. final boolean filterChainsAvailable = (filterChains != null
  577. && filterChains.size() > 0);
  578. if (filterSetsAvailable) {
  579. BufferedReader in = null;
  580. BufferedWriter out = null;
  581. try {
  582. InputStreamReader isr = null;
  583. if (inputEncoding == null) {
  584. isr = new InputStreamReader(source.getInputStream());
  585. } else {
  586. isr = new InputStreamReader(source.getInputStream(),
  587. inputEncoding);
  588. }
  589. in = new BufferedReader(isr);
  590. OutputStreamWriter osw = null;
  591. if (outputEncoding == null) {
  592. osw = new OutputStreamWriter(dest.getOutputStream());
  593. } else {
  594. osw = new OutputStreamWriter(dest.getOutputStream(),
  595. outputEncoding);
  596. }
  597. out = new BufferedWriter(osw);
  598. if (filterChainsAvailable) {
  599. ChainReaderHelper crh = new ChainReaderHelper();
  600. crh.setBufferSize(BUF_SIZE);
  601. crh.setPrimaryReader(in);
  602. crh.setFilterChains(filterChains);
  603. crh.setProject(project);
  604. Reader rdr = crh.getAssembledReader();
  605. in = new BufferedReader(rdr);
  606. }
  607. LineTokenizer lineTokenizer = new LineTokenizer();
  608. lineTokenizer.setIncludeDelims(true);
  609. String newline = null;
  610. String line = lineTokenizer.getToken(in);
  611. while (line != null) {
  612. if (line.length() == 0) {
  613. // this should not happen, because the lines are
  614. // returned with the end of line delimiter
  615. out.newLine();
  616. } else {
  617. newline = filters.replaceTokens(line);
  618. out.write(newline);
  619. }
  620. line = lineTokenizer.getToken(in);
  621. }
  622. } finally {
  623. close(out);
  624. close(in);
  625. }
  626. } else if (filterChainsAvailable
  627. || (inputEncoding != null
  628. && !inputEncoding.equals(outputEncoding))
  629. || (inputEncoding == null && outputEncoding != null)) {
  630. BufferedReader in = null;
  631. BufferedWriter out = null;
  632. try {
  633. InputStreamReader isr = null;
  634. if (inputEncoding == null) {
  635. isr = new InputStreamReader(source.getInputStream());
  636. } else {
  637. isr = new InputStreamReader(source.getInputStream(),
  638. inputEncoding);
  639. }
  640. in = new BufferedReader(isr);
  641. OutputStreamWriter osw = null;
  642. if (outputEncoding == null) {
  643. osw = new OutputStreamWriter(dest.getOutputStream());
  644. } else {
  645. osw = new OutputStreamWriter(dest.getOutputStream(),
  646. outputEncoding);
  647. }
  648. out = new BufferedWriter(osw);
  649. if (filterChainsAvailable) {
  650. ChainReaderHelper crh = new ChainReaderHelper();
  651. crh.setBufferSize(BUF_SIZE);
  652. crh.setPrimaryReader(in);
  653. crh.setFilterChains(filterChains);
  654. crh.setProject(project);
  655. Reader rdr = crh.getAssembledReader();
  656. in = new BufferedReader(rdr);
  657. }
  658. char[] buffer = new char[BUF_SIZE];
  659. while (true) {
  660. int nRead = in.read(buffer, 0, buffer.length);
  661. if (nRead == -1) {
  662. break;
  663. }
  664. out.write(buffer, 0, nRead);
  665. }
  666. } finally {
  667. close(out);
  668. close(in);
  669. }
  670. } else {
  671. InputStream in = null;
  672. OutputStream out = null;
  673. try {
  674. in = source.getInputStream();
  675. out = dest.getOutputStream();
  676. byte[] buffer = new byte[BUF_SIZE];
  677. int count = 0;
  678. do {
  679. out.write(buffer, 0, count);
  680. count = in.read(buffer, 0, buffer.length);
  681. } while (count != -1);
  682. } finally {
  683. close(out);
  684. close(in);
  685. }
  686. }
  687. if (preserveLastModified && dest instanceof Touchable) {
  688. setLastModified((Touchable) dest, source.getLastModified());
  689. }
  690. }
  691. /**
  692. * Calls File.setLastModified(long time). Originally written to
  693. * to dynamically bind to that call on Java1.2+.
  694. *
  695. * @param file the file whose modified time is to be set
  696. * @param time the time to which the last modified time is to be set.
  697. * if this is -1, the current time is used.
  698. */
  699. public void setFileLastModified(File file, long time) {
  700. setLastModified(new FileResource(file), time);
  701. }
  702. /**
  703. * Set the last modified time of an object implementing
  704. * org.apache.tools.ant.types.resources.Touchable .
  705. *
  706. * @param t the Touchable whose modified time is to be set.
  707. * @param time the time to which the last modified time is to be set.
  708. * if this is -1, the current time is used.
  709. */
  710. public void setLastModified(Touchable t, long time) {
  711. t.touch((time < 0) ? System.currentTimeMillis() : time);
  712. }
  713. /**
  714. * Interpret the filename as a file relative to the given file
  715. * unless the filename already represents an absolute filename.
  716. * Differs from <code>new File(file, filename)</code> in that
  717. * the resulting File's path will always be a normalized,
  718. * absolute pathname. Also, if it is determined that
  719. * <code>filename</code> is context-relative, <code>file</code>
  720. * will be discarded and the reference will be resolved using
  721. * available context/state information about the filesystem.
  722. *
  723. * @param file the "reference" file for relative paths. This
  724. * instance must be an absolute file and must not contain
  725. * &quot;./&quot; or &quot;../&quot; sequences (same for \ instead
  726. * of /). If it is null, this call is equivalent to
  727. * <code>new java.io.File(filename).getAbsoluteFile()</code>.
  728. *
  729. * @param filename a file name.
  730. *
  731. * @return an absolute file.
  732. * @throws java.lang.NullPointerException if filename is null.
  733. */
  734. public File resolveFile(File file, String filename) {
  735. if (!isAbsolutePath(filename)) {
  736. char sep = File.separatorChar;
  737. filename = filename.replace('/', sep).replace('\\', sep);
  738. if (isContextRelativePath(filename)) {
  739. file = null;
  740. // on cygwin, our current directory can be a UNC;
  741. // assume user.dir is absolute or all hell breaks loose...
  742. String udir = System.getProperty("user.dir");
  743. if (filename.charAt(0) == sep && udir.charAt(0) == sep) {
  744. filename = dissect(udir)[0] + filename.substring(1);
  745. }
  746. }
  747. filename = new File(file, filename).getAbsolutePath();
  748. }
  749. return normalize(filename);
  750. }
  751. /**
  752. * On DOS and NetWare, the evaluation of certain file
  753. * specifications is context-dependent. These are filenames
  754. * beginning with a single separator (relative to current root directory)
  755. * and filenames with a drive specification and no intervening separator
  756. * (relative to current directory of the specified root).
  757. * @param filename the filename to evaluate.
  758. * @return true if the filename is relative to system context.
  759. * @throws java.lang.NullPointerException if filename is null.
  760. * @since Ant 1.7
  761. */
  762. public static boolean isContextRelativePath(String filename) {
  763. if (!(onDos || onNetWare) || filename.length() == 0) {
  764. return false;
  765. }
  766. char sep = File.separatorChar;
  767. filename = filename.replace('/', sep).replace('\\', sep);
  768. char c = filename.charAt(0);
  769. int len = filename.length();
  770. return (c == sep && (len == 1 || filename.charAt(1) != sep))
  771. || (Character.isLetter(c) && len > 1
  772. && filename.indexOf(':') == 1
  773. && (len == 2 || filename.charAt(2) != sep));
  774. }
  775. /**
  776. * Verifies that the specified filename represents an absolute path.
  777. * Differs from new java.io.File("filename").isAbsolute() in that a path
  778. * beginning with a double file separator--signifying a Windows UNC--must
  779. * at minimum match "\\a\b" to be considered an absolute path.
  780. * @param filename the filename to be checked.
  781. * @return true if the filename represents an absolute path.
  782. * @throws java.lang.NullPointerException if filename is null.
  783. * @since Ant 1.6.3
  784. */
  785. public static boolean isAbsolutePath(String filename) {
  786. int len = filename.length();
  787. if (len == 0) {
  788. return false;
  789. }
  790. char sep = File.separatorChar;
  791. filename = filename.replace('/', sep).replace('\\', sep);
  792. char c = filename.charAt(0);
  793. if (!(onDos || onNetWare)) {
  794. return (c == sep);
  795. }
  796. if (c == sep) {
  797. if (!(onDos && len > 4 && filename.charAt(1) == sep)) {
  798. return false;
  799. }
  800. int nextsep = filename.indexOf(sep, 2);
  801. return nextsep > 2 && nextsep + 1 < len;
  802. }
  803. int colon = filename.indexOf(':');
  804. return (Character.isLetter(c) && colon == 1
  805. && filename.length() > 2 && filename.charAt(2) == sep)
  806. || (onNetWare && colon > 0);
  807. }
  808. /**
  809. * &quot;Normalize&quot; the given absolute path.
  810. *
  811. * <p>This includes:
  812. * <ul>
  813. * <li>Uppercase the drive letter if there is one.</li>
  814. * <li>Remove redundant slashes after the drive spec.</li>
  815. * <li>Resolve all ./, .\, ../ and ..\ sequences.</li>
  816. * <li>DOS style paths that start with a drive letter will have
  817. * \ as the separator.</li>
  818. * </ul>
  819. * Unlike <code>File#getCanonicalPath()</code> this method
  820. * specifically does not resolve symbolic links.
  821. *
  822. * @param path the path to be normalized.
  823. * @return the normalized version of the path.
  824. *
  825. * @throws java.lang.NullPointerException if path is null.
  826. */
  827. public File normalize(final String path) {
  828. Stack s = new Stack();
  829. String[] dissect = dissect(path);
  830. s.push(dissect[0]);
  831. StringTokenizer tok = new StringTokenizer(dissect[1], File.separator);
  832. while (tok.hasMoreTokens()) {
  833. String thisToken = tok.nextToken();
  834. if (".".equals(thisToken)) {
  835. continue;
  836. } else if ("..".equals(thisToken)) {
  837. if (s.size() < 2) {
  838. throw new BuildException("Cannot resolve path " + path);
  839. }
  840. s.pop();
  841. } else { // plain component
  842. s.push(thisToken);
  843. }
  844. }
  845. StringBuffer sb = new StringBuffer();
  846. for (int i = 0; i < s.size(); i++) {
  847. if (i > 1) {
  848. // not before the filesystem root and not after it, since root
  849. // already contains one
  850. sb.append(File.separatorChar);
  851. }
  852. sb.append(s.elementAt(i));
  853. }
  854. return new File(sb.toString());
  855. }
  856. /**
  857. * Dissect the specified absolute path.
  858. * @param path the path to dissect.
  859. * @return String[] {root, remaining path}.
  860. * @throws java.lang.NullPointerException if path is null.
  861. */
  862. public String[] dissect(String path) {
  863. char sep = File.separatorChar;
  864. path = path.replace('/', sep).replace('\\', sep);
  865. // make sure we are dealing with an absolute path
  866. if (!isAbsolutePath(path)) {
  867. throw new BuildException(path + " is not an absolute path");
  868. }
  869. String root = null;
  870. int colon = path.indexOf(':');
  871. if (colon > 0 && (onDos || onNetWare)) {
  872. int next = colon + 1;
  873. root = path.substring(0, next).toUpperCase();
  874. char[] ca = path.toCharArray();
  875. root += sep;
  876. //remove the initial separator; the root has it.
  877. next = (ca[next] == sep) ? next + 1 : next;
  878. StringBuffer sbPath = new StringBuffer();
  879. // Eliminate consecutive slashes after the drive spec:
  880. for (int i = next; i < ca.length; i++) {
  881. if (ca[i] != sep || ca[i - 1] != sep) {
  882. sbPath.append(ca[i]);
  883. }
  884. }
  885. path = sbPath.toString();
  886. } else if (path.length() > 1 && path.charAt(1) == sep) {
  887. // UNC drive
  888. int nextsep = path.indexOf(sep, 2);
  889. nextsep = path.indexOf(sep, nextsep + 1);
  890. root = (nextsep > 2) ? path.substring(0, nextsep + 1) : path;
  891. path = path.substring(root.length());
  892. } else {
  893. root = File.separator;
  894. path = path.substring(1);
  895. }
  896. return new String[] {root, path};
  897. }
  898. /**
  899. * Returns a VMS String representation of a <code>File</code> object.
  900. * This is useful since the JVM by default internally converts VMS paths
  901. * to Unix style.
  902. * The returned String is always an absolute path.
  903. *
  904. * @param f The <code>File</code> to get the VMS path for.
  905. * @return The absolute VMS path to <code>f</code>.
  906. */
  907. public String toVMSPath(File f) {
  908. // format: "DEVICE:[DIR.SUBDIR]FILE"
  909. String osPath;
  910. String path = normalize(f.getAbsolutePath()).getPath();
  911. String name = f.getName();
  912. boolean isAbsolute = path.charAt(0) == File.separatorChar;
  913. // treat directories specified using .DIR syntax as files
  914. boolean isDirectory = f.isDirectory()
  915. && !name.regionMatches(true, name.length() - 4, ".DIR", 0, 4);
  916. String device = null;
  917. StringBuffer directory = null;
  918. String file = null;
  919. int index = 0;
  920. if (isAbsolute) {
  921. index = path.indexOf(File.separatorChar, 1);
  922. if (index == -1) {
  923. return path.substring(1) + ":[000000]";
  924. } else {
  925. device = path.substring(1, index++);
  926. }
  927. }
  928. if (isDirectory) {
  929. directory = new StringBuffer(path.substring(index).
  930. replace(File.separatorChar, '.'));
  931. } else {
  932. int dirEnd =
  933. path.lastIndexOf(File.separatorChar, path.length());
  934. if (dirEnd == -1 || dirEnd < index) {
  935. file = path.substring(index);
  936. } else {
  937. directory = new StringBuffer(path.substring(index, dirEnd).
  938. replace(File.separatorChar, '.'));
  939. index = dirEnd + 1;
  940. if (path.length() > index) {
  941. file = path.substring(index);
  942. }
  943. }
  944. }
  945. if (!isAbsolute && directory != null) {
  946. directory.insert(0, '.');
  947. }
  948. osPath = ((device != null) ? device + ":" : "")
  949. + ((directory != null) ? "[" + directory + "]" : "")
  950. + ((file != null) ? file : "");
  951. return osPath;
  952. }
  953. /**
  954. * Create a temporary file in a given directory.
  955. *
  956. * <p>The file denoted by the returned abstract pathname did not
  957. * exist before this method was invoked, any subsequent invocation
  958. * of this method will yield a different file name.</p>
  959. * <p>
  960. * The filename is prefixNNNNNsuffix where NNNN is a random number.
  961. * </p>
  962. * <p>This method is different from File.createTempFile() of JDK 1.2
  963. * as it doesn't create the file itself. It uses the location pointed
  964. * to by java.io.tmpdir when the parentDir attribute is null.</p>
  965. *
  966. * @param prefix prefix before the random number.
  967. * @param suffix file extension; include the '.'.
  968. * @param parentDir Directory to create the temporary file in;
  969. * java.io.tmpdir used if not specified.
  970. *
  971. * @return a File reference to the new temporary file.
  972. * @since Ant 1.5
  973. */
  974. public File createTempFile(String prefix, String suffix, File parentDir) {
  975. File result = null;
  976. String parent = (parentDir == null)
  977. ? System.getProperty("java.io.tmpdir")
  978. : parentDir.getPath();
  979. DecimalFormat fmt = new DecimalFormat("#####");
  980. synchronized (rand) {
  981. do {
  982. result = new File(parent,
  983. prefix + fmt.format(Math.abs(rand.nextInt()))
  984. + suffix);
  985. } while (result.exists());
  986. }
  987. return result;
  988. }
  989. /**
  990. * Compares the contents of two files.
  991. *
  992. * @param f1 the file whose content is to be compared.
  993. * @param f2 the other file whose content is to be compared.
  994. *
  995. * @return true if the content of the files is the same.
  996. *
  997. * @throws IOException if the files cannot be read.
  998. */
  999. public boolean contentEquals(File f1, File f2) throws IOException {
  1000. return contentEquals(f1, f2, false);
  1001. }
  1002. /**
  1003. * Compares the contents of two files.
  1004. *
  1005. * @param f1 the file whose content is to be compared.
  1006. * @param f2 the other file whose content is to be compared.
  1007. * @param textfile true if the file is to be treated as a text file and
  1008. * differences in kind of line break are to be ignored.
  1009. *
  1010. * @return true if the content of the files is the same.
  1011. *
  1012. * @throws IOException if the files cannot be read.
  1013. * @since Ant 1.6.3
  1014. */
  1015. public boolean contentEquals(File f1, File f2, boolean textfile) throws IOException {
  1016. return contentEquals(new FileResource(f1), new FileResource(f2), textfile);
  1017. }
  1018. /**
  1019. * Compares the contents of two Resources.
  1020. *
  1021. * @param r1 the Resource whose content is to be compared.
  1022. * @param r2 the other Resource whose content is to be compared.
  1023. * @param text true if the content is to be treated as text and
  1024. * differences in kind of line break are to be ignored.
  1025. *
  1026. * @return true if the content of the Resources is the same.
  1027. *
  1028. * @throws IOException if the Resources cannot be read.
  1029. * @since Ant 1.6.3
  1030. */
  1031. public boolean contentEquals(Resource r1, Resource r2, boolean text) throws IOException {
  1032. if (r1.isExists() != r2.isExists()) {
  1033. return false;
  1034. }
  1035. if (!r1.isExists()) {
  1036. // two not existing files are equal
  1037. return true;
  1038. }
  1039. // should the following two be switched? If r1 and r2 refer to the same file,
  1040. // isn't their content equal regardless of whether that file is a directory?
  1041. if (r1.isDirectory() || r2.isDirectory()) {
  1042. // don't want to compare directory contents for now
  1043. return false;
  1044. }
  1045. if (r1.equals(r2)) {
  1046. return true;
  1047. }
  1048. if (!text && r1.getSize() != r2.getSize()) {
  1049. return false;
  1050. }
  1051. return compareContent(r1, r2, text) == 0;
  1052. }
  1053. /**
  1054. * Compare the content of two Resources. A nonexistent Resource's
  1055. * content is "less than" that of an existing Resource; a directory-type
  1056. * Resource's content is "less than" that of a file-type Resource.
  1057. * @param r1 the Resource whose content is to be compared.
  1058. * @param r2 the other Resource whose content is to be compared.
  1059. * @param text true if the content is to be treated as text and
  1060. * differences in kind of line break are to be ignored.
  1061. * @return a negative integer, zero, or a positive integer as the first
  1062. * argument is less than, equal to, or greater than the second.
  1063. * @throws IOException if the Resources cannot be read.
  1064. */
  1065. public int compareContent(Resource r1, Resource r2, boolean text) throws IOException {
  1066. if (r1.equals(r2)) {
  1067. return 0;
  1068. }
  1069. boolean e1 = r1.isExists();
  1070. boolean e2 = r2.isExists();
  1071. if (!(e1 || e2)) {
  1072. return 0;
  1073. }
  1074. if (e1 != e2) {
  1075. return e1 ? 1 : -1;
  1076. }
  1077. boolean d1 = r1.isDirectory();
  1078. boolean d2 = r2.isDirectory();
  1079. if (d1 && d2) {
  1080. return 0;
  1081. }
  1082. if (d1 || d2) {
  1083. return d1 ? -1 : 1;
  1084. }
  1085. return text ? textCompare(r1, r2) : binaryCompare(r1, r2);
  1086. }
  1087. /**
  1088. * Binary compares the contents of two Resources.
  1089. * <p>
  1090. * simple but sub-optimal comparision algorithm. written for working
  1091. * rather than fast. Better would be a block read into buffers followed
  1092. * by long comparisions apart from the final 1-7 bytes.
  1093. * </p>
  1094. *
  1095. * @param r1 the Resource whose content is to be compared.
  1096. * @param r2 the other Resource whose content is to be compared.
  1097. * @return a negative integer, zero, or a positive integer as the first
  1098. * argument is less than, equal to, or greater than the second.
  1099. * @throws IOException if the Resources cannot be read.
  1100. */
  1101. private int binaryCompare(Resource r1, Resource r2) throws IOException {
  1102. InputStream in1 = null;
  1103. InputStream in2 = null;
  1104. try {
  1105. in1 = new BufferedInputStream(r1.getInputStream());
  1106. in2 = new BufferedInputStream(r2.getInputStream());
  1107. for (int b1 = in1.read(); b1 != -1; b1 = in1.read()) {
  1108. int b2 = in2.read();
  1109. if (b1 != b2) {
  1110. return b1 > b2 ? 1 : -1;
  1111. }
  1112. }
  1113. return in2.read() == -1 ? 0 : -1;
  1114. } finally {
  1115. close(in1);
  1116. close(in2);
  1117. }
  1118. }
  1119. /**
  1120. * Text compares the contents of two Resources.
  1121. * Ignores different kinds of line endings.
  1122. * @param r1 the Resource whose content is to be compared.
  1123. * @param r2 the other Resource whose content is to be compared.
  1124. * @return a negative integer, zero, or a positive integer as the first
  1125. * argument is less than, equal to, or greater than the second.
  1126. * @throws IOException if the Resources cannot be read.
  1127. */
  1128. private int textCompare(Resource r1, Resource r2) throws IOException {
  1129. BufferedReader in1 = null;
  1130. BufferedReader in2 = null;
  1131. try {
  1132. in1 = new BufferedReader(new InputStreamReader(r1.getInputStream()));
  1133. in2 = new BufferedReader(new InputStreamReader(r2.getInputStream()));
  1134. String expected = in1.readLine();
  1135. while (expected != null) {
  1136. String actual = in2.readLine();
  1137. if (!expected.equals(actual)) {
  1138. return expected.compareTo(actual);
  1139. }
  1140. expected = in1.readLine();
  1141. }
  1142. return in2.readLine() == null ? 0 : -1;
  1143. } finally {
  1144. close(in1);
  1145. close(in2);
  1146. }
  1147. }
  1148. /**
  1149. * This was originally an emulation of {@link File#getParentFile} for JDK 1.1,
  1150. * but it is now implemented using that method (Ant 1.6.3 onwards).
  1151. * @param f the file whose parent is required.
  1152. * @return the given file's parent, or null if the file does not have a
  1153. * parent.
  1154. * @since 1.10
  1155. * @deprecated Just use {@link File#getParentFile} directly.
  1156. */
  1157. public File getParentFile(File f) {
  1158. return (f == null) ? null : f.getParentFile();
  1159. }
  1160. /**
  1161. * Read from reader till EOF.
  1162. * @param rdr the reader from which to read.
  1163. * @return the contents read out of the given reader.
  1164. *
  1165. * @throws IOException if the contents could not be read out from the
  1166. * reader.
  1167. */
  1168. public static final String readFully(Reader rdr) throws IOException {
  1169. return readFully(rdr, BUF_SIZE);
  1170. }
  1171. /**
  1172. * Read from reader till EOF.
  1173. *
  1174. * @param rdr the reader from which to read.
  1175. * @param bufferSize the buffer size to use when reading.
  1176. *
  1177. * @return the contents read out of the given reader.
  1178. *
  1179. * @throws IOException if the contents could not be read out from the
  1180. * reader.
  1181. */
  1182. public static final String readFully(Reader rdr, int bufferSize)
  1183. throws IOException {
  1184. if (bufferSize <= 0) {
  1185. throw new IllegalArgumentException("Buffer size must be greater "
  1186. + "than 0");
  1187. }
  1188. final char[] buffer = new char[bufferSize];
  1189. int bufferLength = 0;
  1190. StringBuffer textBuffer = null;
  1191. while (bufferLength != -1) {
  1192. bufferLength = rdr.read(buffer);
  1193. if (bufferLength > 0) {
  1194. textBuffer = (textBuffer == null) ? new StringBuffer() : textBuffer;
  1195. textBuffer.append(new String(buffer, 0, bufferLength));
  1196. }
  1197. }
  1198. return (textBuffer == null) ? null : textBuffer.toString();
  1199. }
  1200. /**
  1201. * This was originally an emulation of File.createNewFile for JDK 1.1,
  1202. * but it is now implemented using that method (Ant 1.6.3 onwards).
  1203. *
  1204. * <p>This method has historically <strong>not</strong> guaranteed that the
  1205. * operation was atomic. In its current implementation it is.
  1206. *
  1207. * @param f the file to be created.
  1208. * @return true if the file did not exist already.
  1209. * @throws IOException on error.
  1210. * @since Ant 1.5
  1211. */
  1212. public boolean createNewFile(File f) throws IOException {
  1213. return f.createNewFile();
  1214. }
  1215. /**
  1216. * Create a new file, optionally creating parent directories.
  1217. *
  1218. * @param f the file to be created.
  1219. * @param mkdirs <code>boolean</code> whether to create parent directories.
  1220. * @return true if the file did not exist already.
  1221. * @throws IOException on error.
  1222. * @since Ant 1.6.3
  1223. */
  1224. public boolean createNewFile(File f, boolean mkdirs) throws IOException {
  1225. File parent = f.getParentFile();
  1226. if (mkdirs && !(parent.exists())) {
  1227. parent.mkdirs();
  1228. }
  1229. return f.createNewFile();
  1230. }
  1231. /**
  1232. * Checks whether a given file is a symbolic link.
  1233. *
  1234. * <p>It doesn't really test for symbolic links but whether the
  1235. * canonical and absolute paths of the file are identical--this
  1236. * may lead to false positives on some platforms.</p>
  1237. *
  1238. * @param parent the parent directory of the file to test
  1239. * @param name the name of the file to test.
  1240. *
  1241. * @return true if the file is a symbolic link.
  1242. * @throws IOException on error.
  1243. * @since Ant 1.5
  1244. */
  1245. public boolean isSymbolicLink(File parent, String name)
  1246. throws IOException {
  1247. if (parent == null) {
  1248. File f = new File(name);
  1249. parent = f.getParentFile();
  1250. name = f.getName();
  1251. }
  1252. File toTest = new File(parent.getCanonicalPath(), name);
  1253. return !toTest.getAbsolutePath().equals(toTest.getCanonicalPath());
  1254. }
  1255. /**
  1256. * Removes a leading path from a second path.
  1257. *
  1258. * @param leading The leading path, must not be null, must be absolute.
  1259. * @param path The path to remove from, must not be null, must be absolute.
  1260. *
  1261. * @return path's normalized absolute if it doesn't start with
  1262. * leading; path's path with leading's path removed otherwise.
  1263. *
  1264. * @since Ant 1.5
  1265. */
  1266. public String removeLeadingPath(File leading, File path) {
  1267. String l = normalize(leading.getAbsolutePath()).getAbsolutePath();
  1268. String p = normalize(path.getAbsolutePath()).getAbsolutePath();
  1269. if (l.equals(p)) {
  1270. return "";
  1271. }
  1272. // ensure that l ends with a /
  1273. // so we never think /foo was a parent directory of /foobar
  1274. if (!l.endsWith(File.separator)) {
  1275. l += File.separator;
  1276. }
  1277. return (p.startsWith(l)) ? p.substring(l.length()) : p;
  1278. }
  1279. /**
  1280. * Constructs a <code>file:</code> URI that represents the
  1281. * external form of the given pathname.
  1282. *
  1283. * <p>Will be an absolute URI if the given path is absolute.</p>
  1284. *
  1285. * <p>This code doesn't handle non-ASCII characters properly.</p>
  1286. *
  1287. * @param path the path in the local file system.
  1288. * @return the URI version of the local path.
  1289. * @since Ant 1.6
  1290. */
  1291. public String toURI(String path) {
  1292. boolean isDir = new File(path).isDirectory();
  1293. StringBuffer sb = new StringBuffer("file:");
  1294. path = resolveFile(null, path).getPath();
  1295. sb.append("//");
  1296. // add an extra slash for filesystems with drive-specifiers
  1297. if (!path.startsWith(File.separator)) {
  1298. sb.append("/");
  1299. }
  1300. path = path.replace('\\', '/');
  1301. CharacterIterator iter = new StringCharacterIterator(path);
  1302. for (char c = iter.first(); c != CharacterIterator.DONE;
  1303. c = iter.next()) {
  1304. if (c < 256 && isSpecial[c]) {
  1305. sb.append('%');
  1306. sb.append(escapedChar1[c]);
  1307. sb.append(escapedChar2[c]);
  1308. } else {
  1309. sb.append(c);
  1310. }
  1311. }
  1312. if (isDir && !path.endsWith("/")) {
  1313. sb.append('/');
  1314. }
  1315. return sb.toString();
  1316. }
  1317. /**
  1318. * Constructs a file path from a <code>file:</code> URI.
  1319. *
  1320. * <p>Will be an absolute path if the given URI is absolute.</p>
  1321. *
  1322. * <p>Swallows '%' that are not followed by two characters,
  1323. * doesn't deal with non-ASCII characters.</p>
  1324. *
  1325. * @param uri the URI designating a file in the local filesystem.
  1326. * @return the local file system path for the file.
  1327. * @since Ant 1.6
  1328. */
  1329. public String fromURI(String uri) {
  1330. String path = Locator.fromURI(uri);
  1331. // catch exception if normalize thinks this is not an absolute path
  1332. try {
  1333. path = normalize(path).getAbsolutePath();
  1334. } catch (BuildException e) {
  1335. // relative path
  1336. }
  1337. return path;
  1338. }
  1339. /**
  1340. * Compares two filenames.
  1341. *
  1342. * <p>Unlike java.io.File#equals this method will try to compare
  1343. * the absolute paths and &quot;normalize&quot; the filenames
  1344. * before comparing them.</p>
  1345. *
  1346. * @param f1 the file whose name is to be compared.
  1347. * @param f2 the other file whose name is to be compared.
  1348. *
  1349. * @return true if the file are for the same file.
  1350. *
  1351. * @since Ant 1.5.3
  1352. */
  1353. public boolean fileNameEquals(File f1, File f2) {
  1354. return normalize(f1.getAbsolutePath())
  1355. .equals(normalize(f2.getAbsolutePath()));
  1356. }
  1357. /**
  1358. * Renames a file, even if that involves crossing file system boundaries.
  1359. *
  1360. * <p>This will remove <code>to</code> (if it exists), ensure that
  1361. * <code>to</code>'s parent directory exists and move
  1362. * <code>from</code>, which involves deleting <code>from</code> as
  1363. * well.</p>
  1364. *
  1365. * @param from the file to move.
  1366. * @param to the new file name.
  1367. *
  1368. * @throws IOException if anything bad happens during this
  1369. * process. Note that <code>to</code> may have been deleted
  1370. * already when this happens.
  1371. *
  1372. * @since Ant 1.6
  1373. */
  1374. public void rename(File from, File to) throws IOException {
  1375. if (to.exists() && !to.delete()) {
  1376. throw new IOException("Failed to delete " + to
  1377. + " while trying to rename " + from);
  1378. }
  1379. File parent = to.getParentFile();
  1380. if (parent != null && !parent.exists() && !parent.mkdirs()) {
  1381. throw new IOException("Failed to create directory " + parent
  1382. + " while trying to rename " + from);
  1383. }
  1384. if (!from.renameTo(to)) {
  1385. copyFile(from, to);
  1386. if (!from.delete()) {
  1387. throw new IOException("Failed to delete " + from
  1388. + " while trying to rename it.");
  1389. }
  1390. }
  1391. }
  1392. /**
  1393. * Get the granularity of file timestamps.
  1394. * The choice is made based on OS, which is incorrect--it should really be
  1395. * by filesystem. We do not have an easy way to probe for file systems,
  1396. * however, so this heuristic gives us a decent default.
  1397. * @return the difference, in milliseconds, which two file timestamps must have
  1398. * in order for the two files to be considered to have different timestamps.
  1399. */
  1400. public long getFileTimestampGranularity() {
  1401. if (onWin9x) {
  1402. return FAT_FILE_TIMESTAMP_GRANULARITY;
  1403. } else if (onWindows) {
  1404. return NTFS_FILE_TIMESTAMP_GRANULARITY;
  1405. } else if (onDos) {
  1406. return FAT_FILE_TIMESTAMP_GRANULARITY;
  1407. }
  1408. return UNIX_FILE_TIMESTAMP_GRANULARITY;
  1409. }
  1410. /**
  1411. * Returns true if the source is older than the dest.
  1412. * If the dest file does not exist, then the test returns false; it is
  1413. * implicitly not up do date.
  1414. * @param source source file (should be the older).
  1415. * @param dest dest file (should be the newer).
  1416. * @param granularity an offset added to the source time.
  1417. * @return true if the source is older than the dest after accounting
  1418. * for granularity.
  1419. * @since Ant 1.6.3
  1420. */
  1421. public boolean isUpToDate(File source, File dest, long granularity) {
  1422. //do a check for the destination file existing
  1423. if (!dest.exists()) {
  1424. //if it does not, then the file is not up to date.
  1425. return false;
  1426. }
  1427. long sourceTime = source.lastModified();
  1428. long destTime = dest.lastModified();
  1429. return isUpToDate(sourceTime, destTime, granularity);
  1430. }
  1431. /**
  1432. * Returns true if the source is older than the dest.
  1433. * @param source source file (should be the older).
  1434. * @param dest dest file (should be the newer).
  1435. * @return true if the source is older than the dest, taking the granularity into account.
  1436. * @since Ant 1.6.3
  1437. */
  1438. public boolean isUpToDate(File source, File dest) {
  1439. return isUpToDate(source, dest, getFileTimestampGranularity());
  1440. }
  1441. /**
  1442. * Compare two timestamps for being up to date using
  1443. * the specified granularity.
  1444. *
  1445. * @param sourceTime timestamp of source file.
  1446. * @param destTime timestamp of dest file.
  1447. * @param granularity os/filesys granularity.
  1448. * @return true if the dest file is considered up to date.
  1449. */
  1450. public boolean isUpToDate(long sourceTime, long destTime, long granularity) {
  1451. if (destTime == -1) {
  1452. return false;
  1453. }
  1454. return destTime >= sourceTime + granularity;
  1455. }
  1456. /**
  1457. * Compare two timestamps for being up to date using the
  1458. * current granularity.
  1459. *
  1460. * @param sourceTime timestamp of source file.
  1461. * @param destTime timestamp of dest file.
  1462. * @return true if the dest file is considered up to date.
  1463. */
  1464. public boolean isUpToDate(long sourceTime, long destTime) {
  1465. return isUpToDate(sourceTime, destTime, getFileTimestampGranularity());
  1466. }
  1467. /**
  1468. * Close a Writer without throwing any exception if something went wrong.
  1469. * Do not attempt to close it if the argument is null.
  1470. * @param device output writer, can be null.
  1471. */
  1472. public static void close(Writer device) {
  1473. if (device != null) {
  1474. try {
  1475. device.close();
  1476. } catch (IOException ioex) {
  1477. //ignore
  1478. }
  1479. }
  1480. }
  1481. /**
  1482. * Close a stream without throwing any exception if something went wrong.
  1483. * Do not attempt to close it if the argument is null.
  1484. *
  1485. * @param device Reader, can be null.
  1486. */
  1487. public static void close(Reader device) {
  1488. if (device != null) {
  1489. try {
  1490. device.close();
  1491. } catch (IOException ioex) {
  1492. //ignore
  1493. }
  1494. }
  1495. }
  1496. /**
  1497. * Close a stream without throwing any exception if something went wrong.
  1498. * Do not attempt to close it if the argument is null.
  1499. *
  1500. * @param device stream, can be null.
  1501. */
  1502. public static void close(OutputStream device) {
  1503. if (device != null) {
  1504. try {
  1505. device.close();
  1506. } catch (IOException ioex) {
  1507. //ignore
  1508. }
  1509. }
  1510. }
  1511. /**
  1512. * Close a stream without throwing any exception if something went wrong.
  1513. * Do not attempt to close it if the argument is null.
  1514. *
  1515. * @param device stream, can be null.
  1516. */
  1517. public static void close(InputStream device) {
  1518. if (device != null) {
  1519. try {
  1520. device.close();
  1521. } catch (IOException ioex) {
  1522. //ignore
  1523. }
  1524. }
  1525. }
  1526. /**
  1527. * Delete the file with {@link File#delete()} if the argument is not null.
  1528. * Do nothing on a null argument.
  1529. * @param file file to delete.
  1530. */
  1531. public static void delete(File file) {
  1532. if (file != null) {
  1533. file.delete();
  1534. }
  1535. }
  1536. }