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.

FileUtil.java 46KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  1. /* *******************************************************************
  2. * Copyright (c) 1999-2001 Xerox Corporation,
  3. * 2002 Palo Alto Research Center, Incorporated (PARC).
  4. * All rights reserved.
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Public License v1.0
  7. * which accompanies this distribution and is available at
  8. * http://www.eclipse.org/legal/epl-v10.html
  9. *
  10. * Contributors:
  11. * Xerox/PARC initial implementation
  12. * ******************************************************************/
  13. package org.aspectj.util;
  14. import java.io.BufferedOutputStream;
  15. import java.io.BufferedReader;
  16. import java.io.ByteArrayOutputStream;
  17. import java.io.DataInputStream;
  18. import java.io.DataOutputStream;
  19. import java.io.File;
  20. import java.io.FileFilter;
  21. import java.io.FileInputStream;
  22. import java.io.FileNotFoundException;
  23. import java.io.FileOutputStream;
  24. import java.io.FileReader;
  25. import java.io.FileWriter;
  26. import java.io.FilenameFilter;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.OutputStream;
  30. import java.io.PrintStream;
  31. import java.io.Reader;
  32. import java.io.StringReader;
  33. import java.io.Writer;
  34. import java.net.MalformedURLException;
  35. import java.net.URL;
  36. import java.util.ArrayList;
  37. import java.util.Arrays;
  38. import java.util.Collections;
  39. import java.util.Iterator;
  40. import java.util.LinkedList;
  41. import java.util.List;
  42. import java.util.zip.ZipEntry;
  43. import java.util.zip.ZipFile;
  44. /**
  45. *
  46. */
  47. public class FileUtil {
  48. /** default parent directory File when a file has a null parent */
  49. public static final File DEFAULT_PARENT = new File("."); // XXX user.dir?
  50. /** unmodifiable List of String source file suffixes (including leading ".") */
  51. public static final List<String> SOURCE_SUFFIXES = Collections.unmodifiableList(Arrays.asList(new String[] { ".java", ".aj" }));
  52. public static final FileFilter ZIP_FILTER = new FileFilter() {
  53. public boolean accept(File file) {
  54. return isZipFile(file);
  55. }
  56. public String toString() {
  57. return "ZIP_FILTER";
  58. }
  59. };
  60. // public static final FileFilter SOURCE_FILTER = new FileFilter() {
  61. // public boolean accept(File file) {
  62. // return hasSourceSuffix(file);
  63. // }
  64. //
  65. // public String toString() {
  66. // return "SOURCE_FILTER";
  67. // }
  68. // };
  69. final static int[] INT_RA = new int[0];
  70. /** accept all files */
  71. public static final FileFilter ALL = new FileFilter() {
  72. public boolean accept(File f) {
  73. return true;
  74. }
  75. };
  76. public static final FileFilter DIRS_AND_WRITABLE_CLASSES = new FileFilter() {
  77. public boolean accept(File file) {
  78. return ((null != file) && (file.isDirectory() || (file.canWrite() && file.getName().toLowerCase().endsWith(".class"))));
  79. }
  80. };
  81. private static final boolean PERMIT_CVS;
  82. static {
  83. String name = FileUtil.class.getName() + ".PERMIT_CVS";
  84. PERMIT_CVS = LangUtil.getBoolean(name, false);
  85. }
  86. /** @return true if file exists and is a zip file */
  87. public static boolean isZipFile(File file) {
  88. try {
  89. return (null != file) && new ZipFile(file) != null;
  90. } catch (IOException e) {
  91. return false;
  92. }
  93. }
  94. /** @return true if path ends with .zip or .jar */
  95. // public static boolean hasZipSuffix(String path) {
  96. // return ((null != path) && (0 != zipSuffixLength(path)));
  97. // }
  98. /** @return 0 if file has no zip/jar suffix or 4 otherwise */
  99. public static int zipSuffixLength(File file) {
  100. return (null == file ? 0 : zipSuffixLength(file.getPath()));
  101. }
  102. /** @return 0 if no zip/jar suffix or 4 otherwise */
  103. public static int zipSuffixLength(String path) {
  104. if ((null != path) && (4 < path.length())) {
  105. String test = path.substring(path.length() - 4).toLowerCase();
  106. if (".zip".equals(test) || ".jar".equals(test)) {
  107. return 4;
  108. }
  109. }
  110. return 0;
  111. }
  112. /** @return true if file path has a source suffix */
  113. public static boolean hasSourceSuffix(File file) {
  114. return ((null != file) && hasSourceSuffix(file.getPath()));
  115. }
  116. /** @return true if path ends with .java or .aj */
  117. public static boolean hasSourceSuffix(String path) {
  118. return ((null != path) && (0 != sourceSuffixLength(path)));
  119. }
  120. /**
  121. * @return 0 if file has no source suffix or the length of the suffix otherwise
  122. */
  123. public static int sourceSuffixLength(File file) {
  124. return (null == file ? 0 : sourceSuffixLength(file.getPath()));
  125. }
  126. /** @return 0 if no source suffix or the length of the suffix otherwise */
  127. public static int sourceSuffixLength(String path) {
  128. if (LangUtil.isEmpty(path)) {
  129. return 0;
  130. }
  131. for (Iterator<String> iter = SOURCE_SUFFIXES.iterator(); iter.hasNext();) {
  132. String suffix = iter.next();
  133. if (path.endsWith(suffix) || path.toLowerCase().endsWith(suffix)) {
  134. return suffix.length();
  135. }
  136. }
  137. return 0;
  138. }
  139. /** @return true if this is a readable directory */
  140. public static boolean canReadDir(File dir) {
  141. return ((null != dir) && dir.canRead() && dir.isDirectory());
  142. }
  143. /** @return true if this is a readable file */
  144. public static boolean canReadFile(File file) {
  145. return ((null != file) && file.canRead() && file.isFile());
  146. }
  147. /** @return true if dir is a writable directory */
  148. public static boolean canWriteDir(File dir) {
  149. return ((null != dir) && dir.canWrite() && dir.isDirectory());
  150. }
  151. /** @return true if this is a writable file */
  152. public static boolean canWriteFile(File file) {
  153. return ((null != file) && file.canWrite() && file.isFile());
  154. }
  155. // /**
  156. // * @throws IllegalArgumentException unless file is readable and not a
  157. // * directory
  158. // */
  159. // public static void throwIaxUnlessCanReadFile(File file, String label) {
  160. // if (!canReadFile(file)) {
  161. // throw new IllegalArgumentException(label + " not readable file: " +
  162. // file);
  163. // }
  164. // }
  165. /**
  166. * @throws IllegalArgumentException unless dir is a readable directory
  167. */
  168. public static void throwIaxUnlessCanReadDir(File dir, String label) {
  169. if (!canReadDir(dir)) {
  170. throw new IllegalArgumentException(label + " not readable dir: " + dir);
  171. }
  172. }
  173. /**
  174. * @throws IllegalArgumentException unless file is readable and not a directory
  175. */
  176. public static void throwIaxUnlessCanWriteFile(File file, String label) {
  177. if (!canWriteFile(file)) {
  178. throw new IllegalArgumentException(label + " not writable file: " + file);
  179. }
  180. }
  181. /** @throws IllegalArgumentException unless dir is a readable directory */
  182. public static void throwIaxUnlessCanWriteDir(File dir, String label) {
  183. if (!canWriteDir(dir)) {
  184. throw new IllegalArgumentException(label + " not writable dir: " + dir);
  185. }
  186. }
  187. /** @return array same length as input, with String paths */
  188. public static String[] getPaths(File[] files) {
  189. if ((null == files) || (0 == files.length)) {
  190. return new String[0];
  191. }
  192. String[] result = new String[files.length];
  193. for (int i = 0; i < result.length; i++) {
  194. if (null != files[i]) {
  195. result[i] = files[i].getPath();
  196. }
  197. }
  198. return result;
  199. }
  200. /** @return array same length as input, with String paths */
  201. public static String[] getPaths(List<File> files) {
  202. final int size = (null == files ? 0 : files.size());
  203. if (0 == size) {
  204. return new String[0];
  205. }
  206. String[] result = new String[size];
  207. for (int i = 0; i < size; i++) {
  208. File file = files.get(i);
  209. if (null != file) {
  210. result[i] = file.getPath();
  211. }
  212. }
  213. return result;
  214. }
  215. /**
  216. * Extract the name of a class from the path to its file. If the basedir is null, then the class is assumed to be in the default
  217. * package unless the classFile has one of the top-level suffixes { com, org, java, javax } as a parent directory.
  218. *
  219. * @param basedir the File of the base directory (prefix of classFile)
  220. * @param classFile the File of the class to extract the name for
  221. * @throws IllegalArgumentException if classFile is null or does not end with ".class" or a non-null basedir is not a prefix of
  222. * classFile
  223. */
  224. public static String fileToClassName(File basedir, File classFile) {
  225. LangUtil.throwIaxIfNull(classFile, "classFile");
  226. String classFilePath = normalizedPath(classFile);
  227. if (!classFilePath.endsWith(".class")) {
  228. String m = classFile + " does not end with .class";
  229. throw new IllegalArgumentException(m);
  230. }
  231. classFilePath = classFilePath.substring(0, classFilePath.length() - 6);
  232. if (null != basedir) {
  233. String basePath = normalizedPath(basedir);
  234. if (!classFilePath.startsWith(basePath)) {
  235. String m = classFile + " does not start with " + basedir;
  236. throw new IllegalArgumentException(m);
  237. }
  238. classFilePath = classFilePath.substring(basePath.length() + 1);
  239. } else {
  240. final String[] suffixes = new String[] { "com", "org", "java", "javax" };
  241. boolean found = false;
  242. for (int i = 0; !found && (i < suffixes.length); i++) {
  243. int loc = classFilePath.indexOf(suffixes[i] + "/");
  244. if ((0 == loc) || ((-1 != loc) && ('/' == classFilePath.charAt(loc - 1)))) {
  245. classFilePath = classFilePath.substring(loc);
  246. found = true;
  247. }
  248. }
  249. if (!found) {
  250. int loc = classFilePath.lastIndexOf("/");
  251. if (-1 != loc) { // treat as default package
  252. classFilePath = classFilePath.substring(loc + 1);
  253. }
  254. }
  255. }
  256. return classFilePath.replace('/', '.');
  257. }
  258. /**
  259. * Normalize path for comparisons by rendering absolute, clipping basedir prefix, trimming and changing '\\' to '/'
  260. *
  261. * @param file the File with the path to normalize
  262. * @param basedir the File for the prefix of the file to normalize - ignored if null
  263. * @return "" if null or normalized path otherwise
  264. * @throws IllegalArgumentException if basedir is not a prefix of file
  265. */
  266. public static String normalizedPath(File file, File basedir) {
  267. String filePath = normalizedPath(file);
  268. if (null != basedir) {
  269. String basePath = normalizedPath(basedir);
  270. if (filePath.startsWith(basePath)) {
  271. filePath = filePath.substring(basePath.length());
  272. if (filePath.startsWith("/")) {
  273. filePath = filePath.substring(1);
  274. }
  275. }
  276. }
  277. return filePath;
  278. }
  279. /**
  280. * Render a set of files to String as a path by getting absolute paths of each and delimiting with infix.
  281. *
  282. * @param files the File[] to flatten - may be null or empty
  283. * @param infix the String delimiter internally between entries (if null, then use File.pathSeparator). (alias to
  284. * <code>flatten(getAbsolutePaths(files), infix)</code>
  285. * @return String with absolute paths to entries in order, delimited with infix
  286. */
  287. public static String flatten(File[] files, String infix) {
  288. if (LangUtil.isEmpty(files)) {
  289. return "";
  290. }
  291. return flatten(getPaths(files), infix);
  292. }
  293. /**
  294. * Flatten File[] to String.
  295. *
  296. * @param files the File[] of paths to flatten - null ignored
  297. * @param infix the String infix to use - null treated as File.pathSeparator
  298. */
  299. public static String flatten(String[] paths, String infix) {
  300. if (null == infix) {
  301. infix = File.pathSeparator;
  302. }
  303. StringBuffer result = new StringBuffer();
  304. boolean first = true;
  305. for (int i = 0; i < paths.length; i++) {
  306. String path = paths[i];
  307. if (null == path) {
  308. continue;
  309. }
  310. if (first) {
  311. first = false;
  312. } else {
  313. result.append(infix);
  314. }
  315. result.append(path);
  316. }
  317. return result.toString();
  318. }
  319. /**
  320. * Normalize path for comparisons by rendering absolute trimming and changing '\\' to '/'
  321. *
  322. * @return "" if null or normalized path otherwise
  323. */
  324. public static String normalizedPath(File file) {
  325. return (null == file ? "" : weakNormalize(file.getAbsolutePath()));
  326. }
  327. /**
  328. * Weakly normalize path for comparisons by trimming and changing '\\' to '/'
  329. */
  330. public static String weakNormalize(String path) {
  331. if (null != path) {
  332. path = path.replace('\\', '/').trim();
  333. }
  334. return path;
  335. }
  336. /**
  337. * Get best File for the first-readable path in input paths, treating entries prefixed "sp:" as system property keys. Safe to
  338. * call in static initializers.
  339. *
  340. * @param paths the String[] of paths to check.
  341. * @return null if not found, or valid File otherwise
  342. */
  343. public static File getBestFile(String[] paths) {
  344. if (null == paths) {
  345. return null;
  346. }
  347. File result = null;
  348. for (int i = 0; (null == result) && (i < paths.length); i++) {
  349. String path = paths[i];
  350. if (null == path) {
  351. continue;
  352. }
  353. if (path.startsWith("sp:")) {
  354. try {
  355. path = System.getProperty(path.substring(3));
  356. } catch (Throwable t) {
  357. path = null;
  358. }
  359. if (null == path) {
  360. continue;
  361. }
  362. }
  363. try {
  364. File f = new File(path);
  365. if (f.exists() && f.canRead()) {
  366. result = FileUtil.getBestFile(f);
  367. }
  368. } catch (Throwable t) {
  369. // swallow
  370. }
  371. }
  372. return result;
  373. }
  374. /**
  375. * Render as best file, canonical or absolute.
  376. *
  377. * @param file the File to get the best File for (not null)
  378. * @return File of the best-available path
  379. * @throws IllegalArgumentException if file is null
  380. */
  381. public static File getBestFile(File file) {
  382. LangUtil.throwIaxIfNull(file, "file");
  383. if (file.exists()) {
  384. try {
  385. return file.getCanonicalFile();
  386. } catch (IOException e) {
  387. return file.getAbsoluteFile();
  388. }
  389. } else {
  390. return file;
  391. }
  392. }
  393. /**
  394. * Render as best path, canonical or absolute.
  395. *
  396. * @param file the File to get the path for (not null)
  397. * @return String of the best-available path
  398. * @throws IllegalArgumentException if file is null
  399. */
  400. public static String getBestPath(File file) {
  401. LangUtil.throwIaxIfNull(file, "file");
  402. if (file.exists()) {
  403. try {
  404. return file.getCanonicalPath();
  405. } catch (IOException e) {
  406. return file.getAbsolutePath();
  407. }
  408. } else {
  409. return file.getPath();
  410. }
  411. }
  412. /** @return array same length as input, with String absolute paths */
  413. public static String[] getAbsolutePaths(File[] files) {
  414. if ((null == files) || (0 == files.length)) {
  415. return new String[0];
  416. }
  417. String[] result = new String[files.length];
  418. for (int i = 0; i < result.length; i++) {
  419. if (null != files[i]) {
  420. result[i] = files[i].getAbsolutePath();
  421. }
  422. }
  423. return result;
  424. }
  425. /**
  426. * Recursively delete the contents of dir, but not the dir itself
  427. *
  428. * @return the total number of files deleted
  429. */
  430. public static int deleteContents(File dir) {
  431. return deleteContents(dir, ALL);
  432. }
  433. /**
  434. * Recursively delete some contents of dir, but not the dir itself. This deletes any subdirectory which is empty after its files
  435. * are deleted.
  436. *
  437. * @return the total number of files deleted
  438. */
  439. public static int deleteContents(File dir, FileFilter filter) {
  440. return deleteContents(dir, filter, true);
  441. }
  442. /**
  443. * Recursively delete some contents of dir, but not the dir itself. If deleteEmptyDirs is true, this deletes any subdirectory
  444. * which is empty after its files are deleted.
  445. *
  446. * @param dir the File directory (if a file, the the file is deleted)
  447. * @return the total number of files deleted
  448. */
  449. public static int deleteContents(File dir, FileFilter filter, boolean deleteEmptyDirs) {
  450. if (null == dir) {
  451. throw new IllegalArgumentException("null dir");
  452. }
  453. if ((!dir.exists()) || (!dir.canWrite())) {
  454. return 0;
  455. }
  456. if (!dir.isDirectory()) {
  457. dir.delete();
  458. return 1;
  459. }
  460. String[] fromFiles = dir.list();
  461. int result = 0;
  462. for (int i = 0; i < fromFiles.length; i++) {
  463. String string = fromFiles[i];
  464. File file = new File(dir, string);
  465. if ((null == filter) || filter.accept(file)) {
  466. if (file.isDirectory()) {
  467. result += deleteContents(file, filter, deleteEmptyDirs);
  468. if (deleteEmptyDirs && (0 == file.list().length)) {
  469. file.delete();
  470. }
  471. } else {
  472. /* boolean ret = */file.delete();
  473. result++;
  474. }
  475. }
  476. }
  477. return result;
  478. }
  479. /**
  480. * Copy contents of fromDir into toDir
  481. *
  482. * @param fromDir must exist and be readable
  483. * @param toDir must exist or be creatable and be writable
  484. * @return the total number of files copied
  485. */
  486. public static int copyDir(File fromDir, File toDir) throws IOException {
  487. return copyDir(fromDir, toDir, null, null);
  488. }
  489. /**
  490. * Recursively copy files in fromDir (with any fromSuffix) to toDir, replacing fromSuffix with toSuffix if any. This silently
  491. * ignores dirs and files that are not readable but throw IOException for directories that are not writable. This does not clean
  492. * out the original contents of toDir. (subdirectories are not renamed per directory rules)
  493. *
  494. * @param fromSuffix select files with this suffix - select all if null or empty
  495. * @param toSuffix replace fromSuffix with toSuffix in the destination file name - ignored if null or empty, appended to name if
  496. * fromSuffix is null or empty
  497. * @return the total number of files copied
  498. */
  499. public static int copyDir(File fromDir, File toDir, final String fromSuffix, String toSuffix) throws IOException {
  500. return copyDir(fromDir, toDir, fromSuffix, toSuffix, (FileFilter) null);
  501. }
  502. // /**
  503. // * Recursively copy files in fromDir (with any fromSuffix) to toDir,
  504. // * replacing fromSuffix with toSuffix if any, and adding the destination
  505. // * file to any collector. This silently ignores dirs and files that are
  506. // not
  507. // * readable but throw IOException for directories that are not writable.
  508. // * This does not clean out the original contents of toDir. (subdirectories
  509. // * are not renamed per directory rules) This calls any delegate
  510. // * FilenameFilter to collect any selected file.
  511. // *
  512. // * @param fromSuffix select files with this suffix - select all if null or
  513. // * empty
  514. // * @param toSuffix replace fromSuffix with toSuffix in the destination
  515. // file
  516. // * name - ignored if null or empty, appended to name if
  517. // * fromSuffix is null or empty
  518. // * @param collector the List sink for destination files - ignored if null
  519. // * @return the total number of files copied
  520. // */
  521. // public static int copyDir(File fromDir, File toDir, final String
  522. // fromSuffix, final String toSuffix, final List collector)
  523. // throws IOException {
  524. // // int before = collector.size();
  525. // if (null == collector) {
  526. // return copyDir(fromDir, toDir, fromSuffix, toSuffix);
  527. // } else {
  528. // FileFilter collect = new FileFilter() {
  529. // public boolean accept(File pathname) {
  530. // return collector.add(pathname);
  531. // }
  532. // };
  533. // return copyDir(fromDir, toDir, fromSuffix, toSuffix, collect);
  534. // }
  535. // }
  536. /**
  537. * Recursively copy files in fromDir (with any fromSuffix) to toDir, replacing fromSuffix with toSuffix if any. This silently
  538. * ignores dirs and files that are not readable but throw IOException for directories that are not writable. This does not clean
  539. * out the original contents of toDir. (subdirectories are not renamed per directory rules) This calls any delegate
  540. * FilenameFilter to collect any selected file.
  541. *
  542. * @param fromSuffix select files with this suffix - select all if null or empty
  543. * @param toSuffix replace fromSuffix with toSuffix in the destination file name - ignored if null or empty, appended to name if
  544. * fromSuffix is null or empty
  545. * @return the total number of files copied
  546. */
  547. public static int copyDir(File fromDir, File toDir, final String fromSuffix, final String toSuffix, final FileFilter delegate)
  548. throws IOException {
  549. if ((null == fromDir) || (!fromDir.canRead())) {
  550. return 0;
  551. }
  552. final boolean haveSuffix = ((null != fromSuffix) && (0 < fromSuffix.length()));
  553. final int slen = (!haveSuffix ? 0 : fromSuffix.length());
  554. if (!toDir.exists()) {
  555. toDir.mkdirs();
  556. }
  557. final String[] fromFiles;
  558. if (!haveSuffix) {
  559. fromFiles = fromDir.list();
  560. } else {
  561. FilenameFilter filter = new FilenameFilter() {
  562. public boolean accept(File dir, String name) {
  563. return (new File(dir, name).isDirectory() || (name.endsWith(fromSuffix)));
  564. }
  565. };
  566. fromFiles = fromDir.list(filter);
  567. }
  568. int result = 0;
  569. final int MAX = (null == fromFiles ? 0 : fromFiles.length);
  570. for (int i = 0; i < MAX; i++) {
  571. String filename = fromFiles[i];
  572. File fromFile = new File(fromDir, filename);
  573. if (fromFile.canRead()) {
  574. if (fromFile.isDirectory()) {
  575. result += copyDir(fromFile, new File(toDir, filename), fromSuffix, toSuffix, delegate);
  576. } else if (fromFile.isFile()) {
  577. if (haveSuffix) {
  578. filename = filename.substring(0, filename.length() - slen);
  579. }
  580. if (null != toSuffix) {
  581. filename = filename + toSuffix;
  582. }
  583. File targetFile = new File(toDir, filename);
  584. if ((null == delegate) || delegate.accept(targetFile)) {
  585. copyFile(fromFile, targetFile);
  586. }
  587. result++;
  588. }
  589. }
  590. }
  591. return result;
  592. }
  593. /**
  594. * Recursively list files in srcDir.
  595. *
  596. * @return ArrayList with String paths of File under srcDir (relative to srcDir)
  597. */
  598. public static String[] listFiles(File srcDir) {
  599. ArrayList<String> result = new ArrayList<String>();
  600. if ((null != srcDir) && srcDir.canRead()) {
  601. listFiles(srcDir, null, result);
  602. }
  603. return result.toArray(new String[0]);
  604. }
  605. public static final FileFilter aspectjSourceFileFilter = new FileFilter() {
  606. public boolean accept(File pathname) {
  607. String name = pathname.getName().toLowerCase();
  608. return name.endsWith(".java") || name.endsWith(".aj");
  609. }
  610. };
  611. /**
  612. * Recursively list files in srcDir.
  613. *
  614. * @return ArrayList with String paths of File under srcDir (relative to srcDir)
  615. */
  616. public static File[] listFiles(File srcDir, FileFilter fileFilter) {
  617. ArrayList<File> result = new ArrayList<File>();
  618. if ((null != srcDir) && srcDir.canRead()) {
  619. listFiles(srcDir, result, fileFilter);
  620. }
  621. return result.toArray(new File[result.size()]);
  622. }
  623. /**
  624. * Recursively list .class files in specified directory
  625. *
  626. * @return List of File objects
  627. */
  628. public static List<File> listClassFiles(File dir) {
  629. ArrayList<File> result = new ArrayList<File>();
  630. if ((null != dir) && dir.canRead()) {
  631. listClassFiles(dir, result);
  632. }
  633. return result;
  634. }
  635. /**
  636. * Convert String[] paths to File[] as offset of base directory
  637. *
  638. * @param basedir the non-null File base directory for File to create with paths
  639. * @param paths the String[] of paths to create
  640. * @return File[] with same length as paths
  641. */
  642. public static File[] getBaseDirFiles(File basedir, String[] paths) {
  643. return getBaseDirFiles(basedir, paths, (String[]) null);
  644. }
  645. /**
  646. * Convert String[] paths to File[] as offset of base directory
  647. *
  648. * @param basedir the non-null File base directory for File to create with paths
  649. * @param paths the String[] of paths to create
  650. * @param suffixes the String[] of suffixes to limit sources to - ignored if null
  651. * @return File[] with same length as paths
  652. */
  653. public static File[] getBaseDirFiles(File basedir, String[] paths, String[] suffixes) {
  654. LangUtil.throwIaxIfNull(basedir, "basedir");
  655. LangUtil.throwIaxIfNull(paths, "paths");
  656. File[] result = null;
  657. if (!LangUtil.isEmpty(suffixes)) {
  658. ArrayList<File> list = new ArrayList<File>();
  659. for (int i = 0; i < paths.length; i++) {
  660. String path = paths[i];
  661. for (int j = 0; j < suffixes.length; j++) {
  662. if (path.endsWith(suffixes[j])) {
  663. list.add(new File(basedir, paths[i]));
  664. break;
  665. }
  666. }
  667. }
  668. result = list.toArray(new File[0]);
  669. } else {
  670. result = new File[paths.length];
  671. for (int i = 0; i < result.length; i++) {
  672. result[i] = newFile(basedir, paths[i]);
  673. }
  674. }
  675. return result;
  676. }
  677. /**
  678. * Create a new File, resolving paths ".." and "." specially.
  679. *
  680. * @param dir the File for the parent directory of the file
  681. * @param path the path in the parent directory (filename only?)
  682. * @return File for the new file.
  683. */
  684. private static File newFile(File dir, String path) {
  685. if (".".equals(path)) {
  686. return dir;
  687. } else if ("..".equals(path)) {
  688. File parentDir = dir.getParentFile();
  689. if (null != parentDir) {
  690. return parentDir;
  691. } else {
  692. return new File(dir, "..");
  693. }
  694. } else {
  695. return new File(dir, path);
  696. }
  697. }
  698. /**
  699. * Copy files from source dir into destination directory, creating any needed directories. This differs from copyDir in not
  700. * being recursive; each input with the source dir creates a full path. However, if the source is a directory, it is copied as
  701. * such.
  702. *
  703. * @param srcDir an existing, readable directory containing relativePaths files
  704. * @param relativePaths a set of paths relative to srcDir to readable File to copy
  705. * @param destDir an existing, writable directory to copy files to
  706. * @throws IllegalArgumentException if input invalid, IOException if operations fail
  707. */
  708. public static File[] copyFiles(File srcDir, String[] relativePaths, File destDir) throws IllegalArgumentException, IOException {
  709. final String[] paths = relativePaths;
  710. throwIaxUnlessCanReadDir(srcDir, "srcDir");
  711. throwIaxUnlessCanWriteDir(destDir, "destDir");
  712. LangUtil.throwIaxIfNull(paths, "relativePaths");
  713. File[] result = new File[paths.length];
  714. for (int i = 0; i < paths.length; i++) {
  715. String path = paths[i];
  716. LangUtil.throwIaxIfNull(path, "relativePaths-entry");
  717. File src = newFile(srcDir, paths[i]);
  718. File dest = newFile(destDir, path);
  719. File destParent = dest.getParentFile();
  720. if (!destParent.exists()) {
  721. destParent.mkdirs();
  722. }
  723. LangUtil.throwIaxIfFalse(canWriteDir(destParent), "dest-entry-parent");
  724. copyFile(src, dest); // both file-dir and dir-dir copies
  725. result[i] = dest;
  726. }
  727. return result;
  728. }
  729. /**
  730. * Copy fromFile to toFile, handling file-file, dir-dir, and file-dir copies.
  731. *
  732. * @param fromFile the File path of the file or directory to copy - must be readable
  733. * @param toFile the File path of the target file or directory - must be writable (will be created if it does not exist)
  734. */
  735. public static void copyFile(File fromFile, File toFile) throws IOException {
  736. LangUtil.throwIaxIfNull(fromFile, "fromFile");
  737. LangUtil.throwIaxIfNull(toFile, "toFile");
  738. LangUtil.throwIaxIfFalse(!toFile.equals(fromFile), "same file");
  739. if (toFile.isDirectory()) { // existing directory
  740. throwIaxUnlessCanWriteDir(toFile, "toFile");
  741. if (fromFile.isFile()) { // file-dir
  742. File targFile = new File(toFile, fromFile.getName());
  743. copyValidFiles(fromFile, targFile);
  744. } else if (fromFile.isDirectory()) { // dir-dir
  745. copyDir(fromFile, toFile);
  746. } else {
  747. LangUtil.throwIaxIfFalse(false, "not dir or file: " + fromFile);
  748. }
  749. } else if (toFile.isFile()) { // target file exists
  750. if (fromFile.isDirectory()) {
  751. LangUtil.throwIaxIfFalse(false, "can't copy to file dir: " + fromFile);
  752. }
  753. copyValidFiles(fromFile, toFile); // file-file
  754. } else { // target file is a non-existent path -- could be file or dir
  755. /* File toFileParent = */ensureParentWritable(toFile);
  756. if (fromFile.isFile()) {
  757. copyValidFiles(fromFile, toFile);
  758. } else if (fromFile.isDirectory()) {
  759. toFile.mkdirs();
  760. throwIaxUnlessCanWriteDir(toFile, "toFile");
  761. copyDir(fromFile, toFile);
  762. } else {
  763. LangUtil.throwIaxIfFalse(false, "not dir or file: " + fromFile);
  764. }
  765. }
  766. }
  767. /**
  768. * Ensure that the parent directory to path can be written. If the path has a null parent, DEFAULT_PARENT is tested. If the path
  769. * parent does not exist, this tries to create it.
  770. *
  771. * @param path the File path whose parent should be writable
  772. * @return the File path of the writable parent directory
  773. * @throws IllegalArgumentException if parent cannot be written or path is null.
  774. */
  775. public static File ensureParentWritable(File path) {
  776. LangUtil.throwIaxIfNull(path, "path");
  777. File pathParent = path.getParentFile();
  778. if (null == pathParent) {
  779. pathParent = DEFAULT_PARENT;
  780. }
  781. if (!pathParent.canWrite()) {
  782. pathParent.mkdirs();
  783. }
  784. throwIaxUnlessCanWriteDir(pathParent, "pathParent");
  785. return pathParent;
  786. }
  787. /**
  788. * Copy file to file.
  789. *
  790. * @param fromFile the File to copy (readable, non-null file)
  791. * @param toFile the File to copy to (non-null, parent dir exists)
  792. * @throws IOException
  793. */
  794. public static void copyValidFiles(File fromFile, File toFile) throws IOException {
  795. FileInputStream in = null;
  796. FileOutputStream out = null;
  797. try {
  798. in = new FileInputStream(fromFile);
  799. out = new FileOutputStream(toFile);
  800. copyStream(in, out);
  801. } finally {
  802. if (out != null) {
  803. out.close();
  804. }
  805. if (in != null) {
  806. in.close();
  807. }
  808. }
  809. }
  810. /** do line-based copying */
  811. public static void copyStream(DataInputStream in, PrintStream out) throws IOException {
  812. LangUtil.throwIaxIfNull(in, "in");
  813. LangUtil.throwIaxIfNull(in, "out");
  814. String s;
  815. while (null != (s = in.readLine())) {
  816. out.println(s);
  817. }
  818. }
  819. public static void copyStream(InputStream in, OutputStream out) throws IOException {
  820. final int MAX = 4096;
  821. byte[] buf = new byte[MAX];
  822. for (int bytesRead = in.read(buf, 0, MAX); bytesRead != -1; bytesRead = in.read(buf, 0, MAX)) {
  823. out.write(buf, 0, bytesRead);
  824. }
  825. }
  826. public static void copyStream(Reader in, Writer out) throws IOException {
  827. final int MAX = 4096;
  828. char[] buf = new char[MAX];
  829. for (int bytesRead = in.read(buf, 0, MAX); bytesRead != -1; bytesRead = in.read(buf, 0, MAX)) {
  830. out.write(buf, 0, bytesRead);
  831. }
  832. }
  833. /**
  834. * Make a new child directory of parent
  835. *
  836. * @param parent a File for the parent (writable)
  837. * @param child a prefix for the child directory
  838. * @return a File dir that exists with parentDir as the parent file or null
  839. */
  840. public static File makeNewChildDir(File parent, String child) {
  841. if (null == parent || !parent.canWrite() || !parent.isDirectory()) {
  842. throw new IllegalArgumentException("bad parent: " + parent);
  843. } else if (null == child) {
  844. child = "makeNewChildDir";
  845. } else if (!isValidFileName(child)) {
  846. throw new IllegalArgumentException("bad child: " + child);
  847. }
  848. File result = new File(parent, child);
  849. int safety = 1000;
  850. for (String suffix = FileUtil.randomFileString(); ((0 < --safety) && result.exists()); suffix = FileUtil.randomFileString()) {
  851. result = new File(parent, child + suffix);
  852. }
  853. if (result.exists()) {
  854. System.err.println("exhausted files for child dir in " + parent);
  855. return null;
  856. }
  857. return ((result.mkdirs() && result.exists()) ? result : null);
  858. }
  859. /**
  860. * Make a new temporary directory in the same directory that the system uses for temporary files, or if that files, in the
  861. * current directory.
  862. *
  863. * @param name the preferred (simple) name of the directory - may be null.
  864. * @return File of an existing new temp dir, or null if unable to create
  865. */
  866. public static File getTempDir(String name) {
  867. if (null == name) {
  868. name = "FileUtil_getTempDir";
  869. } else if (!isValidFileName(name)) {
  870. throw new IllegalArgumentException(" invalid: " + name);
  871. }
  872. File result = null;
  873. File tempFile = null;
  874. try {
  875. tempFile = File.createTempFile("ignoreMe", ".txt");
  876. File tempParent = tempFile.getParentFile();
  877. result = makeNewChildDir(tempParent, name);
  878. } catch (IOException t) {
  879. result = makeNewChildDir(new File("."), name);
  880. } finally {
  881. if (null != tempFile) {
  882. tempFile.delete();
  883. }
  884. }
  885. return result;
  886. }
  887. public static URL[] getFileURLs(File[] files) {
  888. if ((null == files) || (0 == files.length)) {
  889. return new URL[0];
  890. }
  891. URL[] result = new URL[files.length]; // XXX dangerous non-copy...
  892. for (int i = 0; i < result.length; i++) {
  893. result[i] = getFileURL(files[i]);
  894. }
  895. return result;
  896. }
  897. /**
  898. * Get URL for a File. This appends "/" for directories. prints errors to System.err
  899. *
  900. * @param file the File to convert to URL (not null)
  901. */
  902. public static URL getFileURL(File file) {
  903. LangUtil.throwIaxIfNull(file, "file");
  904. URL result = null;
  905. try {
  906. result = file.toURL();// TODO AV - was toURI.toURL that does not
  907. // works on Java 1.3
  908. if (null != result) {
  909. return result;
  910. }
  911. String url = "file:" + file.getAbsolutePath().replace('\\', '/');
  912. result = new URL(url + (file.isDirectory() ? "/" : ""));
  913. } catch (MalformedURLException e) {
  914. String m = "Util.makeURL(\"" + file.getPath() + "\" MUE " + e.getMessage();
  915. System.err.println(m);
  916. }
  917. return result;
  918. }
  919. /**
  920. * Write contents to file, returning null on success or error message otherwise. This tries to make any necessary parent
  921. * directories first.
  922. *
  923. * @param file the File to write (not null)
  924. * @param contents the String to write (use "" if null)
  925. * @return String null on no error, error otherwise
  926. */
  927. public static String writeAsString(File file, String contents) {
  928. LangUtil.throwIaxIfNull(file, "file");
  929. if (null == contents) {
  930. contents = "";
  931. }
  932. Writer out = null;
  933. try {
  934. File parentDir = file.getParentFile();
  935. if (!parentDir.exists() && !parentDir.mkdirs()) {
  936. return "unable to make parent dir for " + file;
  937. }
  938. Reader in = new StringReader(contents);
  939. out = new FileWriter(file);
  940. FileUtil.copyStream(in, out);
  941. return null;
  942. } catch (IOException e) {
  943. return LangUtil.unqualifiedClassName(e) + " writing " + file + ": " + e.getMessage();
  944. } finally {
  945. if (null != out) {
  946. try {
  947. out.close();
  948. } catch (IOException e) {
  949. } // ignored
  950. }
  951. }
  952. }
  953. /**
  954. * Reads a boolean array with our encoding
  955. */
  956. public static boolean[] readBooleanArray(DataInputStream s) throws IOException {
  957. int len = s.readInt();
  958. boolean[] ret = new boolean[len];
  959. for (int i = 0; i < len; i++) {
  960. ret[i] = s.readBoolean();
  961. }
  962. return ret;
  963. }
  964. /**
  965. * Writes a boolean array with our encoding
  966. */
  967. public static void writeBooleanArray(boolean[] a, DataOutputStream s) throws IOException {
  968. int len = a.length;
  969. s.writeInt(len);
  970. for (int i = 0; i < len; i++) {
  971. s.writeBoolean(a[i]);
  972. }
  973. }
  974. /**
  975. * Reads an int array with our encoding
  976. */
  977. public static int[] readIntArray(DataInputStream s) throws IOException {
  978. int len = s.readInt();
  979. int[] ret = new int[len];
  980. for (int i = 0; i < len; i++) {
  981. ret[i] = s.readInt();
  982. }
  983. return ret;
  984. }
  985. /**
  986. * Writes an int array with our encoding
  987. */
  988. public static void writeIntArray(int[] a, DataOutputStream s) throws IOException {
  989. int len = a.length;
  990. s.writeInt(len);
  991. for (int i = 0; i < len; i++) {
  992. s.writeInt(a[i]);
  993. }
  994. }
  995. /**
  996. * Reads an int array with our encoding
  997. */
  998. public static String[] readStringArray(DataInputStream s) throws IOException {
  999. int len = s.readInt();
  1000. String[] ret = new String[len];
  1001. for (int i = 0; i < len; i++) {
  1002. ret[i] = s.readUTF();
  1003. }
  1004. return ret;
  1005. }
  1006. /**
  1007. * Writes an int array with our encoding
  1008. */
  1009. public static void writeStringArray(String[] a, DataOutputStream s) throws IOException {
  1010. if (a == null) {
  1011. s.writeInt(0);
  1012. return;
  1013. }
  1014. int len = a.length;
  1015. s.writeInt(len);
  1016. for (int i = 0; i < len; i++) {
  1017. s.writeUTF(a[i]);
  1018. }
  1019. }
  1020. /**
  1021. * Returns the contents of this file as a String
  1022. */
  1023. public static String readAsString(File file) throws IOException {
  1024. BufferedReader r = new BufferedReader(new FileReader(file));
  1025. StringBuffer b = new StringBuffer();
  1026. while (true) {
  1027. int ch = r.read();
  1028. if (ch == -1) {
  1029. break;
  1030. }
  1031. b.append((char) ch);
  1032. }
  1033. r.close();
  1034. return b.toString();
  1035. }
  1036. // /**
  1037. // * Returns the contents of this stream as a String
  1038. // */
  1039. // public static String readAsString(InputStream in) throws IOException {
  1040. // BufferedReader r = new BufferedReader(new InputStreamReader(in));
  1041. // StringBuffer b = new StringBuffer();
  1042. // while (true) {
  1043. // int ch = r.read();
  1044. // if (ch == -1)
  1045. // break;
  1046. // b.append((char) ch);
  1047. // }
  1048. // in.close();
  1049. // r.close();
  1050. // return b.toString();
  1051. // }
  1052. /**
  1053. * Returns the contents of this file as a byte[]
  1054. */
  1055. public static byte[] readAsByteArray(File file) throws IOException {
  1056. FileInputStream in = new FileInputStream(file);
  1057. byte[] ret = FileUtil.readAsByteArray(in);
  1058. in.close();
  1059. return ret;
  1060. }
  1061. /**
  1062. * Reads this input stream and returns contents as a byte[]
  1063. */
  1064. public static byte[] readAsByteArray(InputStream inStream) throws IOException {
  1065. int size = 1024;
  1066. byte[] ba = new byte[size];
  1067. int readSoFar = 0;
  1068. while (true) {
  1069. int nRead = inStream.read(ba, readSoFar, size - readSoFar);
  1070. if (nRead == -1) {
  1071. break;
  1072. }
  1073. readSoFar += nRead;
  1074. if (readSoFar == size) {
  1075. int newSize = size * 2;
  1076. byte[] newBa = new byte[newSize];
  1077. System.arraycopy(ba, 0, newBa, 0, size);
  1078. ba = newBa;
  1079. size = newSize;
  1080. }
  1081. }
  1082. byte[] newBa = new byte[readSoFar];
  1083. System.arraycopy(ba, 0, newBa, 0, readSoFar);
  1084. return newBa;
  1085. }
  1086. final static String FILECHARS = "abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1087. /** @return semi-random String of length 6 usable as filename suffix */
  1088. static String randomFileString() {
  1089. final double FILECHARS_length = FILECHARS.length();
  1090. final int LEN = 6;
  1091. final char[] result = new char[LEN];
  1092. int index = (int) (Math.random() * 6d);
  1093. for (int i = 0; i < LEN; i++) {
  1094. if (index >= LEN) {
  1095. index = 0;
  1096. }
  1097. result[index++] = FILECHARS.charAt((int) (Math.random() * FILECHARS_length));
  1098. }
  1099. return new String(result);
  1100. }
  1101. public static InputStream getStreamFromZip(String zipFile, String name) {
  1102. try {
  1103. ZipFile zf = new ZipFile(zipFile);
  1104. try {
  1105. ZipEntry entry = zf.getEntry(name);
  1106. return zf.getInputStream(entry);
  1107. } finally {
  1108. // ??? is it safe not to close this zf.close();
  1109. }
  1110. } catch (IOException ioe) {
  1111. return null;
  1112. }
  1113. }
  1114. //
  1115. // public static void extractJar(String zipFile, String outDir) throws
  1116. // IOException {
  1117. // ZipInputStream zs = new ZipInputStream(new FileInputStream(zipFile));
  1118. // ZipEntry entry;
  1119. // while ((entry = zs.getNextEntry()) != null) {
  1120. // if (entry.isDirectory())
  1121. // continue;
  1122. // byte[] in = readAsByteArray(zs);
  1123. //
  1124. // File outFile = new File(outDir + "/" + entry.getName());
  1125. // // if (!outFile.getParentFile().exists())
  1126. // // System.err.println("parent: " + outFile.getParentFile());
  1127. // // System.err.println("parent: " + outFile.getParentFile());
  1128. // outFile.getParentFile().mkdirs();
  1129. // FileOutputStream os = new FileOutputStream(outFile);
  1130. // os.write(in);
  1131. // os.close();
  1132. // zs.closeEntry();
  1133. // }
  1134. // zs.close();
  1135. // }
  1136. /**
  1137. * Do line-based search for literal text in source files, returning file:line where found.
  1138. *
  1139. * @param sought the String text to seek in the file
  1140. * @param sources the List of String paths to the source files
  1141. * @param listAll if false, only list first match in file
  1142. * @param errorSink the PrintStream to print any errors to (one per line) (use null to silently ignore errors)
  1143. * @return List of String of the form file:line for each found entry (never null, might be empty)
  1144. */
  1145. // OPTIMIZE only used by tests? move it out
  1146. public static List<String> lineSeek(String sought, List<String> sources, boolean listAll, PrintStream errorSink) {
  1147. if (LangUtil.isEmpty(sought) || LangUtil.isEmpty(sources)) {
  1148. return Collections.emptyList();
  1149. }
  1150. ArrayList<String> result = new ArrayList<String>();
  1151. for (Iterator<String> iter = sources.iterator(); iter.hasNext();) {
  1152. String path = iter.next();
  1153. String error = lineSeek(sought, path, listAll, result);
  1154. if ((null != error) && (null != errorSink)) {
  1155. errorSink.println(error);
  1156. }
  1157. }
  1158. return result;
  1159. }
  1160. /**
  1161. * Do line-based search for literal text in source file, returning line where found as a String in the form
  1162. * {sourcePath}:line:column submitted to the collecting parameter sink. Any error is rendered to String and returned as the
  1163. * result.
  1164. *
  1165. * @param sought the String text to seek in the file
  1166. * @param sources the List of String paths to the source files
  1167. * @param listAll if false, only list first match in file
  1168. * @param List sink the List for String entries of the form {sourcePath}:line:column
  1169. * @return String error if any, or add String entries to sink
  1170. */
  1171. public static String lineSeek(String sought, String sourcePath, boolean listAll, ArrayList<String> sink) {
  1172. if (LangUtil.isEmpty(sought) || LangUtil.isEmpty(sourcePath)) {
  1173. return "nothing sought";
  1174. }
  1175. if (LangUtil.isEmpty(sourcePath)) {
  1176. return "no sourcePath";
  1177. }
  1178. final File file = new File(sourcePath);
  1179. if (!file.canRead() || !file.isFile()) {
  1180. return "sourcePath not a readable file";
  1181. }
  1182. int lineNum = 0;
  1183. FileReader fin = null;
  1184. try {
  1185. fin = new FileReader(file);
  1186. BufferedReader reader = new BufferedReader(fin);
  1187. String line;
  1188. while (null != (line = reader.readLine())) {
  1189. lineNum++;
  1190. int loc = line.indexOf(sought);
  1191. if (-1 != loc) {
  1192. sink.add(sourcePath + ":" + lineNum + ":" + loc);
  1193. if (!listAll) {
  1194. break;
  1195. }
  1196. }
  1197. }
  1198. } catch (IOException e) {
  1199. return LangUtil.unqualifiedClassName(e) + " reading " + sourcePath + ":" + lineNum;
  1200. } finally {
  1201. try {
  1202. if (null != fin) {
  1203. fin.close();
  1204. }
  1205. } catch (IOException e) {
  1206. } // ignore
  1207. }
  1208. return null;
  1209. }
  1210. public static BufferedOutputStream makeOutputStream(File file) throws FileNotFoundException {
  1211. File parent = file.getParentFile();
  1212. if (parent != null) {
  1213. parent.mkdirs();
  1214. }
  1215. return new BufferedOutputStream(new FileOutputStream(file));
  1216. }
  1217. /**
  1218. * Sleep until after the last last-modified stamp from the files.
  1219. *
  1220. * @param files the File[] of files to inspect for last modified times (this ignores null or empty files array and null or
  1221. * non-existing components of files array)
  1222. * @return true if succeeded without 100 interrupts
  1223. */
  1224. public static boolean sleepPastFinalModifiedTime(File[] files) {
  1225. if ((null == files) || (0 == files.length)) {
  1226. return true;
  1227. }
  1228. long delayUntil = System.currentTimeMillis();
  1229. for (int i = 0; i < files.length; i++) {
  1230. File file = files[i];
  1231. if ((null == file) || !file.exists()) {
  1232. continue;
  1233. }
  1234. long nextModTime = file.lastModified();
  1235. if (nextModTime > delayUntil) {
  1236. delayUntil = nextModTime;
  1237. }
  1238. }
  1239. return LangUtil.sleepUntil(++delayUntil);
  1240. }
  1241. private static void listClassFiles(final File baseDir, ArrayList<File> result) {
  1242. File[] files = baseDir.listFiles();
  1243. for (int i = 0; i < files.length; i++) {
  1244. File f = files[i];
  1245. if (f.isDirectory()) {
  1246. listClassFiles(f, result);
  1247. } else {
  1248. if (f.getName().endsWith(".class")) {
  1249. result.add(f);
  1250. }
  1251. }
  1252. }
  1253. }
  1254. private static void listFiles(final File baseDir, ArrayList<File> result, FileFilter filter) {
  1255. File[] files = baseDir.listFiles();
  1256. // hack https://bugs.eclipse.org/bugs/show_bug.cgi?id=48650
  1257. final boolean skipCVS = (!PERMIT_CVS && (filter == aspectjSourceFileFilter));
  1258. for (int i = 0; i < files.length; i++) {
  1259. File f = files[i];
  1260. if (f.isDirectory()) {
  1261. if (skipCVS) {
  1262. String name = f.getName().toLowerCase();
  1263. if ("cvs".equals(name) || "sccs".equals(name)) {
  1264. continue;
  1265. }
  1266. }
  1267. listFiles(f, result, filter);
  1268. } else {
  1269. if (filter.accept(f)) {
  1270. result.add(f);
  1271. }
  1272. }
  1273. }
  1274. }
  1275. /** @return true if input is not null and contains no path separator */
  1276. private static boolean isValidFileName(String input) {
  1277. return ((null != input) && (-1 == input.indexOf(File.pathSeparator)));
  1278. }
  1279. private static void listFiles(final File baseDir, String dir, ArrayList<String> result) {
  1280. final String dirPrefix = (null == dir ? "" : dir + "/");
  1281. final File dirFile = (null == dir ? baseDir : new File(baseDir.getPath() + "/" + dir));
  1282. final String[] files = dirFile.list();
  1283. for (int i = 0; i < files.length; i++) {
  1284. File f = new File(dirFile, files[i]);
  1285. String path = dirPrefix + files[i];
  1286. if (f.isDirectory()) {
  1287. listFiles(baseDir, path, result);
  1288. } else {
  1289. result.add(path);
  1290. }
  1291. }
  1292. }
  1293. private FileUtil() {
  1294. }
  1295. public static List<String> makeClasspath(URL[] urls) {
  1296. List<String> ret = new LinkedList<String>();
  1297. if (urls != null) {
  1298. for (int i = 0; i < urls.length; i++) {
  1299. ret.add(urls[i].getPath());
  1300. }
  1301. }
  1302. return ret;
  1303. }
  1304. /**
  1305. * A pipe when run reads from an input stream to an output stream, optionally sleeping between reads.
  1306. *
  1307. * @see #copyStream(InputStream, OutputStream)
  1308. */
  1309. public static class Pipe implements Runnable {
  1310. private final InputStream in;
  1311. private final OutputStream out;
  1312. private final long sleep;
  1313. private ByteArrayOutputStream snoop;
  1314. private long totalWritten;
  1315. private Throwable thrown;
  1316. private boolean halt;
  1317. /**
  1318. * Seem to be unable to detect erroroneous closing of System.out...
  1319. */
  1320. private final boolean closeInput;
  1321. private final boolean closeOutput;
  1322. /**
  1323. * If true, then continue processing stream until no characters are returned when halting.
  1324. */
  1325. private boolean finishStream;
  1326. private boolean done; // true after completing() completes
  1327. /**
  1328. * alias for <code>Pipe(in, out, 100l, false, false)</code>
  1329. *
  1330. * @param in the InputStream source to read
  1331. * @param out the OutputStream sink to write
  1332. */
  1333. Pipe(InputStream in, OutputStream out) {
  1334. this(in, out, 100l, false, false);
  1335. }
  1336. /**
  1337. * @param in the InputStream source to read
  1338. * @param out the OutputStream sink to write
  1339. * @param tryClosingStreams if true, then try closing both streams when done
  1340. * @param sleep milliseconds to delay between reads (pinned to 0..1 minute)
  1341. */
  1342. Pipe(InputStream in, OutputStream out, long sleep, boolean closeInput, boolean closeOutput) {
  1343. LangUtil.throwIaxIfNull(in, "in");
  1344. LangUtil.throwIaxIfNull(out, "out");
  1345. this.in = in;
  1346. this.out = out;
  1347. this.closeInput = closeInput;
  1348. this.closeOutput = closeOutput;
  1349. this.sleep = Math.min(0l, Math.max(60l * 1000l, sleep));
  1350. }
  1351. public void setSnoop(ByteArrayOutputStream snoop) {
  1352. this.snoop = snoop;
  1353. }
  1354. /**
  1355. * Run the pipe. This halts on the first Throwable thrown or when a read returns -1 (for end-of-file) or on demand.
  1356. */
  1357. public void run() {
  1358. totalWritten = 0;
  1359. if (halt) {
  1360. return;
  1361. }
  1362. try {
  1363. final int MAX = 4096;
  1364. byte[] buf = new byte[MAX];
  1365. // TODO this blocks, hanging the harness
  1366. int count = in.read(buf, 0, MAX);
  1367. ByteArrayOutputStream mySnoop;
  1368. while ((halt && finishStream && (0 < count)) || (!halt && (-1 != count))) {
  1369. out.write(buf, 0, count);
  1370. mySnoop = snoop;
  1371. if (null != mySnoop) {
  1372. mySnoop.write(buf, 0, count);
  1373. }
  1374. totalWritten += count;
  1375. if (halt && !finishStream) {
  1376. break;
  1377. }
  1378. if (!halt && (0 < sleep)) {
  1379. Thread.sleep(sleep);
  1380. }
  1381. if (halt && !finishStream) {
  1382. break;
  1383. }
  1384. count = in.read(buf, 0, MAX);
  1385. }
  1386. } catch (Throwable e) {
  1387. thrown = e;
  1388. } finally {
  1389. halt = true;
  1390. if (closeInput) {
  1391. try {
  1392. in.close();
  1393. } catch (IOException e) {
  1394. // ignore
  1395. }
  1396. }
  1397. if (closeOutput) {
  1398. try {
  1399. out.close();
  1400. } catch (IOException e) {
  1401. // ignore
  1402. }
  1403. }
  1404. done = true;
  1405. completing(totalWritten, thrown);
  1406. }
  1407. }
  1408. /**
  1409. * Tell the pipe to halt the next time it gains control.
  1410. *
  1411. * @param wait if true, this waits synchronously until pipe is done
  1412. * @param finishStream if true, then continue until a read from the input stream returns no bytes, then halt.
  1413. * @return true if <code>run()</code> will return the next time it gains control
  1414. */
  1415. public boolean halt(boolean wait, boolean finishStream) {
  1416. if (!halt) {
  1417. halt = true;
  1418. }
  1419. if (wait) {
  1420. while (!done) {
  1421. synchronized (this) {
  1422. notifyAll();
  1423. }
  1424. if (!done) {
  1425. try {
  1426. Thread.sleep(5l);
  1427. } catch (InterruptedException e) {
  1428. break;
  1429. }
  1430. }
  1431. }
  1432. }
  1433. return halt;
  1434. }
  1435. /** @return the total number of bytes written */
  1436. public long totalWritten() {
  1437. return totalWritten;
  1438. }
  1439. /** @return any exception thrown when reading/writing */
  1440. public Throwable getThrown() {
  1441. return thrown;
  1442. }
  1443. /**
  1444. * This is called when the pipe is completing. This implementation does nothing. Subclasses implement this to get notice.
  1445. * Note that halt(true, true) might or might not have completed before this method is called.
  1446. */
  1447. protected void completing(long totalWritten, Throwable thrown) {
  1448. }
  1449. }
  1450. }