Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 39c3efed1c655a70d1d36cbcef7126aca57dd8c5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
/*******************************************************************************
 * Copyright (c) 2005, 2007 Oracle. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0, which accompanies this distribution
 * and is available at http://www.eclipse.org/legal/epl-v10.html.
 * 
 * Contributors:
 *     Oracle - initial API and implementation
 ******************************************************************************/
package org.eclipse.jpt.utility.internal;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.jpt.utility.internal.iterators.ArrayIterator;
import org.eclipse.jpt.utility.internal.iterators.CompositeIterator;
import org.eclipse.jpt.utility.internal.iterators.FilteringIterator;
import org.eclipse.jpt.utility.internal.iterators.TransformationIterator;

/**
 * Assorted file tools:
 * - delete entire trees of directories and files
 * - build iterators on entire trees of directories and files
 * - build a temporary directory
 * - "canonize" files
 */
public final class FileTools {

	public static final String USER_HOME_DIRECTORY_NAME = System.getProperty("user.home");
	public static final String USER_TEMPORARY_DIRECTORY_NAME = System.getProperty("java.io.tmpdir");
	public static String DEFAULT_TEMPORARY_DIRECTORY_NAME = "tmpdir";
	public static final String CURRENT_WORKING_DIRECTORY_NAME = System.getProperty("user.dir");

    /** A list of some invalid file name characters.
				: is the filename separator in MacOS and the drive indicator in DOS
				* is a DOS wildcard character
				| is a DOS redirection character
				& is our own escape character
				/ is the filename separator in Unix and the command option tag in DOS
				\ is the filename separator in DOS/Windows and the escape character in Unix
				; is ???
				? is a DOS wildcard character
				[ is ???
				] is ???
				= is ???
				+ is ???
				< is a DOS redirection character
				> is a DOS redirection character
				" is used by DOS to delimit file names with spaces
				, is ???
     */
	public static final char[] INVALID_FILENAME_CHARACTERS = { ':', '*', '|', '&', '/', '\\', ';', '?', '[', ']', '=', '+', '<', '>', '"', ',' };

	/** This encoder will convert strings into valid file names. */
	public static final XMLStringEncoder FILE_NAME_ENCODER = new XMLStringEncoder(INVALID_FILENAME_CHARACTERS);

	/** Windows files that are redirected to devices etc. */
	private static final String[] WINDOWS_RESERVED_FILE_NAMES = {
		"con",
		"aux",
		"com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9",
		"lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9",
		"prn",
		"nul"
	};

	/** The default length of a shortened file name. */
	public static final int MAXIMUM_SHORTENED_FILE_NAME_LENGTH = 60;


	// ********** deleting directories **********

	/**
	 * Delete the specified directory and all of its contents.
	 * <em>USE WITH CARE.</em>
	 * File#deleteAll()?
	 */
	public static void deleteDirectory(String directoryName) {
		deleteDirectory(new File(directoryName));
	}
	
	/**
	 * Delete the specified directory and all of its contents.
	 * <em>USE WITH CARE.</em>
	 * File#deleteAll()?
	 */
	public static void deleteDirectory(File directory) {
		deleteDirectoryContents(directory);
		if ( ! directory.delete()) {
			throw new RuntimeException("unable to delete directory: " + directory.getAbsolutePath());
		}
	}
	
	/**
	 * Delete the contents of the specified directory
	 * (but not the directory itself).
	 * <em>USE WITH CARE.</em>
	 * File#deleteFiles()
	 */
	public static void deleteDirectoryContents(String directoryName) {
		deleteDirectoryContents(new File(directoryName));
	}
	
	/**
	 * Delete the contents of the specified directory
	 * (but not the directory itself).
	 * <em>USE WITH CARE.</em>
	 * File#deleteFiles()
	 */
	public static void deleteDirectoryContents(File directory) {
		for (File file : directory.listFiles()) {
			if (file.isDirectory()) {
				deleteDirectory(file);	// recurse through subdirectories
			} else {
				if ( ! file.delete()) {
					throw new RuntimeException("unable to delete file: " + file.getAbsolutePath());
				}
			}
		}
	}
	

	// ********** copying files **********

	/**
	 * Copies the content of the source file to the destination file.
	 * File#copy(File destinationFile)
	 */
	public static void copyToFile(File sourceFile, File destinationFile)
		throws IOException
	{
		FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel();
		FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel();
		try {
			destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
		} finally {
			sourceChannel.close();
			destinationChannel.close();
		}
	}
	
	/**
	 * Copies the content of the source file to a file by
	 * the same name in the destination directory.
	 * File#copyToDirectory(File destinationDirectory)
	 */
	public static void copyToDirectory(File sourceFile, File destinationDirectory)
		throws IOException
	{
		File destinationFile = new File(destinationDirectory, sourceFile.getName());
		destinationFile.createNewFile();
		copyToFile(sourceFile, destinationFile);
	}
	

	// ********** iteratoring over files and directories **********

	/**
	 * Return an iterator on all the files in the specified directory.
	 * The iterator will skip over subdirectories.
	 * File#files()
	 */
	public static Iterator<File> filesIn(String directoryName) {
		return filesIn(new File(directoryName));
	}
	
	/**
	 * Return an iterator on all the files in the specified directory.
	 * The iterator will skip over subdirectories.
	 * File#files()
	 */
	public static Iterator<File> filesIn(File directory) {
		return filesIn(directory.listFiles());
	}
	
	private static Iterator<File> filesIn(File[] files) {
		return new FilteringIterator<File>(new ArrayIterator<File>(files)) {
			@Override
			protected boolean accept(Object next) {
				return ((File) next).isFile();
			}
		};
	}
	
	/**
	 * Return an iterator on all the subdirectories
	 * in the specified directory.
	 * File#subDirectories()
	 */
	public static Iterator<File> directoriesIn(String directoryName) {
		return directoriesIn(new File(directoryName));
	}
	
	/**
	 * Return an iterator on all the subdirectories
	 * in the specified directory.
	 * File#subDirectories()
	 */
	public static Iterator<File> directoriesIn(File directory) {
		return directoriesIn(directory.listFiles());
	}
	
	private static Iterator<File> directoriesIn(File[] files) {
		return new FilteringIterator<File>(new ArrayIterator<File>(files)) {
			@Override
			protected boolean accept(Object next) {
				return ((File) next).isDirectory();
			}
		};
	}
	
	/**
	 * Return an iterator on all the files under the specified
	 * directory, recursing into subdirectories.
	 * The iterator will skip over the subdirectories themselves.
	 * File#filesRecurse()
	 */
	public static Iterator<File> filesInTree(String directoryName) {
		return filesInTree(new File(directoryName));
	}
	
	/**
	 * Return an iterator on all the files under the specified
	 * directory, recursing into subdirectories.
	 * The iterator will skip over the subdirectories themselves.
	 * File#filesRecurse()
	 */
	public static Iterator<File> filesInTree(File directory) {
		return filesInTreeAsSet(directory).iterator();
	}

	private static Set<File> filesInTreeAsSet(File directory) {
		Set<File> files = new HashSet<File>(10000);
		addFilesInTreeTo(directory, files);
		return files;
	}

	private static void addFilesInTreeTo(File directory, Collection<File> allFiles) {
		for (File file : directory.listFiles()) {
			if (file.isFile()) {
				allFiles.add(file);
			} else if (file.isDirectory()) {
				addFilesInTreeTo(file, allFiles);
			}
		}
	}

	/**
	 * Return an iterator on all the directories under the specified
	 * directory, recursing into subdirectories.
	 * File#subDirectoriesRecurse()
	 */
	public static Iterator<File> directoriesInTree(String directoryName) {
		return directoriesInTree(new File(directoryName));
	}
	
	/**
	 * Return an iterator on all the directories under the specified
	 * directory, recursing into subdirectories.
	 * File#subDirectoriesRecurse()
	 */
	@SuppressWarnings("unchecked")
	public static Iterator<File> directoriesInTree(File directory) {
		File[] files = directory.listFiles();
		return new CompositeIterator<File>(directoriesIn(files), directoriesInTrees(directoriesIn(files)));
	}
	
	private static Iterator<File> directoriesInTrees(Iterator<File> directories) {
		return new CompositeIterator<File>(
			new TransformationIterator<File, Iterator<File>>(directories) {
				@Override
				protected Iterator<File> transform(File next) {
					return FileTools.directoriesInTree(next);
				}
			}
		);
	}
	

	// ********** short file name manipulation **********

	/**
	 * Strip the extension from the specified file name
	 * and return the result. If the file name has no
	 * extension, it is returned unchanged
	 * File#basePath()
	 */
	public static String stripExtension(String fileName) {
		int index = fileName.lastIndexOf('.');
		if (index == -1) {
			return fileName;
		}
		return fileName.substring(0, index);
	}
	
	/**
	 * Strip the extension from the specified file's name
	 * and return the result. If the file's name has no
	 * extension, it is returned unchanged
	 * File#basePath()
	 */
	public static String stripExtension(File file) {
		return stripExtension(file.getPath());
	}

	/**
	 * Return the extension, including the dot, of the specified file name.
	 * If the file name has no extension, return an empty string.
	 * File#extension()
	 */
	public static String extension(String fileName) {
		int index = fileName.lastIndexOf('.');
		if (index == -1) {
			return "";
		}
		return fileName.substring(index);
	}
	
	/**
	 * Return the extension, including the dot, of the specified file's name.
	 * If the file's name has no extension, return an empty string.
	 * File#extension()
	 */
	public static String extension(File file) {
		return extension(file.getPath());
	}


	// ********** temporary directories **********

	/**
	 * Build and return an empty temporary directory with the specified
	 * name. If the directory already exists, it will be cleared out.
	 * This directory will be a subdirectory of the Java temporary directory,
	 * as indicated by the System property "java.io.tmpdir".
	 */
	public static File emptyTemporaryDirectory(String name) {
		File dir = new File(userTemporaryDirectory(), name);
		if (dir.exists()) {
			deleteDirectoryContents(dir);
		} else {
			dir.mkdirs();
		}
		return dir;
	}
	
	/**
	 * Build and return an empty temporary directory with a
	 * name of "tmpdir". If the directory already exists, it will be cleared out.
	 * This directory will be a subdirectory of the Java temporary directory,
	 * as indicated by the System property "java.io.tmpdir".
	 */
	public static File emptyTemporaryDirectory() {
		return emptyTemporaryDirectory(DEFAULT_TEMPORARY_DIRECTORY_NAME);
	}
	
	/**
	 * Build and return a temporary directory with the specified
	 * name. If the directory already exists, it will be left unchanged;
	 * if it does not already exist, it will be created.
	 * This directory will be a subdirectory of the Java temporary directory,
	 * as indicated by the System property "java.io.tmpdir".
	 */
	public static File temporaryDirectory(String name) {
		File dir = new File(userTemporaryDirectory(), name);
		if ( ! dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}
	
	/**
	 * Build and return a temporary directory with a name of
	 * "tmpdir". If the directory already exists, it will be left unchanged;
	 * if it does not already exist, it will be created.
	 * This directory will be a subdirectory of the Java temporary directory,
	 * as indicated by the System property "java.io.tmpdir".
	 */
	public static File temporaryDirectory() {
		return temporaryDirectory(DEFAULT_TEMPORARY_DIRECTORY_NAME);
	}
	
	/**
	 * Build and return a *new* temporary directory with the specified
	 * prefix. The prefix will be appended with a number that
	 * is incremented, starting with 1, until a non-pre-existing directory
	 * is found and successfully created. This directory will be a
	 * subdirectory of the Java temporary directory, as indicated by
	 * the System property "java.io.tmpdir".
	 */
	public static File newTemporaryDirectory(String prefix) {
		if ( ! prefix.endsWith(".")) {
			prefix = prefix + ".";
		}
		File dir;
		int i = 0;
		do {
			i++;
			dir = new File(userTemporaryDirectory(), prefix + i);
		} while ( ! dir.mkdirs());
		return dir;
	}
	
	/**
	 * Build and return a *new* temporary directory with a
	 * prefix of "tmpdir". This prefix will be appended with a number that
	 * is incremented, starting with 1, until a non-pre-existing directory
	 * is found and successfully created. This directory will be a
	 * subdirectory of the Java temporary directory, as indicated by
	 * the System property "java.io.tmpdir".
	 */
	public static File newTemporaryDirectory() {
		return newTemporaryDirectory(DEFAULT_TEMPORARY_DIRECTORY_NAME);
	}
	

	// ********** resource files **********

	/**
	 * Build and return a file for the specified resource.
	 * The resource name must be fully-qualified, i.e. it cannot be relative
	 * to the package name/directory.
	 * NB: There is a bug in jdk1.4.x the prevents us from getting
	 * a resource that has spaces (or other special characters) in
	 * its name.... (see Sun's Java bug 4466485)
	 */
	public static File resourceFile(String resourceName) throws URISyntaxException {
		if ( ! resourceName.startsWith("/")) {
			throw new IllegalArgumentException(resourceName);
		}
		return resourceFile(resourceName, FileTools.class);
	}
	
	/**
	 * Build and return a file for the specified resource.
	 * NB: There is a bug in jdk1.4.x the prevents us from getting
	 * a resource that has spaces (or other special characters) in
	 * its name.... (see Sun's Java bug 4466485)
	 */
	public static File resourceFile(String resourceName, Class<?> javaClass) throws URISyntaxException {
		URL url = javaClass.getResource(resourceName);
		return buildFile(url);
	}
	
	/**
	 * Build and return a file for the specified URL.
	 * NB: There is a bug in jdk1.4.x the prevents us from getting
	 * a resource that has spaces (or other special characters) in
	 * its name.... (see Sun's Java bug 4466485)
	 */
	public static File buildFile(URL url) throws URISyntaxException {
		return buildFile(url.getFile());
	}
	
	/**
	 * Build and return a file for the specified file name.
	 * NB: There is a bug in jdk1.4.x the prevents us from getting
	 * a resource that has spaces (or other special characters) in
	 * its name.... (see Sun's Java bug 4466485)
	 */
	public static File buildFile(String fileName) throws URISyntaxException {
		URI uri = new URI(fileName);
		File file = new File(uri.getPath());
		return file;
	}
	

	// ********** "canonical" files **********

	/**
	 * Convert the specified file into a "canonical" file.
	 */
	public static File canonicalFile(File file) {
		try {
			return file.getCanonicalFile();
		} catch (IOException ioexception) {
			// settle for the absolute file
			return file.getAbsoluteFile();
		}
	}
	
	/**
	 * Build an iterator that will convert the specified files
	 * into "canonical" files.
	 */
	public static Iterator<File> canonicalFiles(Iterator<File> files) {
		return new TransformationIterator<File, File>(files) {
			@Override
			protected File transform(File next) {
				return canonicalFile(next);
			}
		};
	}
	
	/**
	 * Build an iterator that will convert the specified files
	 * into "canonical" files.
	 */
	public static Iterator<File> canonicalFiles(Collection<File> files) {
		return canonicalFiles(files.iterator());
	}
	
	/**
	 * Convert the specified file name into a "canonical" file name.
	 */
	public static String canonicalFileName(String fileName) {
		return canonicalFile(new File(fileName)).getAbsolutePath();
	}
	
	/**
	 * Build an iterator that will convert the specified file names
	 * into "canonical" file names.
	 */
	public static Iterator<String> canonicalFileNames(Iterator<String> fileNames) {
		return new TransformationIterator<String, String>(fileNames) {
			@Override
			protected String transform(String next) {
				return canonicalFileName(next);
			}
		};
	}
	
	/**
	 * Build an iterator that will convert the specified file names
	 * into "canonical" file names.
	 */
	public static Iterator<String> canonicalFileNames(Collection<String> fileNames) {
		return canonicalFileNames(fileNames.iterator());
	}
	

	// ********** file name validation **********

	/**
	 * Return whether the specified file name is invalid.
	 */
	public static boolean fileNameIsInvalid(String filename) {
		return ! fileNameIsValid(filename);
	}

	/**
	 * Return whether the specified file name is valid.
	 */
	public static boolean fileNameIsValid(String filename) {
		int len = filename.length();
		for (int i = 0; i < len; i++) {
			char filenameChar = filename.charAt(i);
			if (CollectionTools.contains(INVALID_FILENAME_CHARACTERS, filenameChar)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Convert the illegal characters in the specified file name to
	 * the specified character and return the result.
	 */
	public static String convertToValidFileName(String filename, char replacementChar) {
		int len = filename.length();
		StringBuffer sb = new StringBuffer(len);
		for (int i = 0; i < len; i++) {
			char filenameChar = filename.charAt(i);
			if (CollectionTools.contains(INVALID_FILENAME_CHARACTERS, filenameChar)) {
				sb.append(replacementChar);
			} else {
				sb.append(filenameChar);
			}
		}
		return sb.toString();
	}

	/**
	 * Convert the illegal characters in the specified file name to
	 * periods ('.') and return the result.
	 */
	public static String convertToValidFileName(String filename) {
		return convertToValidFileName(filename, '.');
	}

	/**
	 * Return whether the specified file name is "reserved"
	 * (i.e. it cannot be used for "user" files). Windows reserves
	 * a number of file names (e.g. CON, AUX, PRN).
	 */
	public static boolean fileNameIsReserved(String fileName) {
		if (executingOnWindows()) {
			return CollectionTools.contains(WINDOWS_RESERVED_FILE_NAMES, fileName.toLowerCase());
		}
		return false;	// Unix does not have any "reserved" file names (I think...)
	}

	/**
	 * Return whether the specified file contains any "reserved"
	 * components.
	 * Windows reserves a number of file names (e.g. CON, AUX, PRN);
	 * and these file names cannot be used for either the names of
	 * files or directories.
	 */
	public static boolean fileHasAnyReservedComponents(File file) {
		File temp = file;
		while (temp != null) {
			if (fileNameIsReserved(temp.getName())) {
				return true;
			}
			temp = temp.getParentFile();
		}
		return false;
	}


	// ********** shortened file names **********

	/**
	 * Return a shorter version of the absolute file name for the specified file.
	 * The shorter version will not be longer than the maximum length.
	 * The first directory (usually the drive letter) and the file name or the
	 * last directory will always be added to the generated string regardless of
	 * the maximum length allowed.
	 */
	public static String shortenFileName(URL url) {
		return shortenFileName(url, MAXIMUM_SHORTENED_FILE_NAME_LENGTH);
	}

	/**
	 * Return a shorter version of the absolute file name for the specified file.
	 * The shorter version will not be longer than the maximum length.
	 * The first directory (usually the drive letter) and the file name or the
	 * last directory will always be added to the generated string regardless of
	 * the maximum length allowed.
	 */
	public static String shortenFileName(URL url, int maxLength) {
		File file;
		try {
			file = buildFile(url);
		} catch (URISyntaxException e) {
			file = new File(url.getFile());
		}
		return shortenFileName(file, maxLength);
	}

	/**
	 * Return a shorter version of the absolute file name for the specified file.
	 * The shorter version will not be longer than the maximum length.
	 * The first directory (usually the drive letter) and the file name or the
	 * last directory will always be added to the generated string regardless of
	 * the maximum length allowed.
	 */
	public static String shortenFileName(File file) {
		return shortenFileName(file, MAXIMUM_SHORTENED_FILE_NAME_LENGTH);
	}

	/**
	 * Return a shorter version of the absolute file name for the specified file.
	 * The shorter version will not be longer than the maximum length.
	 * The first directory (usually the drive letter) and the file name or the
	 * last directory will always be added to the generated string regardless of
	 * the maximum length allowed.
	 */
	public static String shortenFileName(File file, int maxLength) {
		String absoluteFileName = canonicalFile(file).getAbsolutePath();
		if (absoluteFileName.length() <= maxLength) {
			// no need to shorten
			return absoluteFileName;
		}

		// break down the path into its components
		String fs = File.separator;
		String[] paths = absoluteFileName.split("\\" + fs);

		if (paths.length <= 1) {
			// e.g. "C:\"
			return paths[0];
		}

		if (paths.length == 2) {
			// e.g. "C:\MyReallyLongFileName.ext" or "C:\MyReallyLongDirectoryName"
			// return the complete file name since this is a minimum requirement,
			// regardless of the maximum length allowed
			return absoluteFileName;
		}

		StringBuffer sb = new StringBuffer();
		sb.append(paths[0]);		// always add the first directory, which is usually the drive letter

		// Keep the index of insertion into the string buffer
		int insertIndex = sb.length();

		sb.append(fs);
		sb.append(paths[paths.length - 1]);		// append the file name or the last directory

		maxLength -= 4;                      // -4 for "/..."

		int currentLength = sb.length() - 4; // -4 for "/..."
		int leftIndex = 1;                   //  1 to skip the root directory
		int rightIndex = paths.length - 2;   // -1 for the file name or the last directory

		boolean canAddFromLeft = true;
		boolean canAddFromRight = true;

		// Add each directory, the insertion is going in both direction: left and
		// right, once a side can't be added, the other side is still continuing
		// until both can't add anymore
		while (true) {
			if (!canAddFromLeft && !canAddFromRight)
				break;

			if (canAddFromRight) {
				String rightDirectory = paths[rightIndex];
				int rightLength = rightDirectory.length();

				// Add the directory on the right side of the loop
				if (currentLength + rightLength + 1 <= maxLength) {
					sb.insert(insertIndex,     fs);
					sb.insert(insertIndex + 1, rightDirectory);

					currentLength += rightLength + 1;
					rightIndex--;

					// The right side is now overlapping the left side, that means
					// we can't add from the right side anymore
					if (leftIndex >= rightIndex) {
						canAddFromRight = false;
					}
				} else {
					canAddFromRight = false;
				}
			}

			if (canAddFromLeft) {
				String leftDirectory = paths[leftIndex];
				int leftLength = leftDirectory.length();

				// Add the directory on the left side of the loop
				if (currentLength + leftLength + 1 <= maxLength) {
					sb.insert(insertIndex,     fs);
					sb.insert(insertIndex + 1, leftDirectory);

					insertIndex += leftLength + 1;
					currentLength += leftLength + 1;
					leftIndex++;

					// The left side is now overlapping the right side, that means
					// we can't add from the left side anymore
					if (leftIndex >= rightIndex) {
						canAddFromLeft = false;
					}
				} else {
					canAddFromLeft = false;
				}
			}
		}

		if (leftIndex <= rightIndex) {
			sb.insert(insertIndex, fs);
			sb.insert(insertIndex + 1, "...");
		}

		return sb.toString();
	}


	// ********** system properties **********

	/**
	 * Return a file representing the user's home directory.
	 */
	public static File userHomeDirectory() {
		return new File(USER_HOME_DIRECTORY_NAME);
	}
	
	/**
	 * Return a file representing the user's temporary directory.
	 */
	public static File userTemporaryDirectory() {
		return new File(USER_TEMPORARY_DIRECTORY_NAME);
	}
	
	/**
	 * Return a file representing the current working directory.
	 */
	public static File currentWorkingDirectory() {
		return new File(CURRENT_WORKING_DIRECTORY_NAME);
	}
	

	// ********** miscellaneous **********

	private static boolean executingOnWindows() {
		return executingOn("Windows");
	}

//	private static boolean executingOnLinux() {
//		return executingOn("Linux");
//	}
//
	private static boolean executingOn(String osName) {
		return System.getProperty("os.name").indexOf(osName) != -1;
	}

	/**
	 * Return only the files that fit the filter.
	 * File#files(FileFilter fileFilter)
	 */
	public static Iterator<File> filter(Iterator<File> files, final FileFilter fileFilter) {
		return new FilteringIterator<File>(files) {
			@Override
			protected boolean accept(Object next) {
				return fileFilter.accept((File) next);
			}
		};
	}

	/**
	 * Return a file that is a re-specification of the specified
	 * file, relative to the specified directory.
	 *     Linux/Unix/Mac:
	 *         convertToRelativeFile(/foo/bar/baz.java, /foo)
	 *             => bar/baz.java
	 *     Windows:
	 *         convertToRelativeFile(C:\foo\bar\baz.java, C:\foo)
	 *             => bar/baz.java
	 * The file can be either a file or a directory; the directory
	 * *should* be a directory.
	 * If the file is already relative or it cannot be made relative
	 * to the directory, it will be returned unchanged.
	 * 
	 * NB: This method has been tested on Windows and Linux,
	 * but not Mac (but the Mac is Unix-based these days, so
	 * it shouldn't be a problem...).
	 */
	public static File convertToRelativeFile(final File file, final File dir) {
		// check whether the file is already relative
		if ( ! file.isAbsolute()) {
			return file;		// return unchanged
		}

		File cFile = canonicalFile(file);
		File cDir = canonicalFile(dir);

		// the two are the same directory
		if (cFile.equals(cDir)) {
			return new File(".");
		}

		File[] filePathFiles = pathFiles(cFile);
		File[] dirPathFiles = pathFiles(cDir);

		// Windows only (?): the roots are different - e.g. D:\ vs. C:\
		if ( ! dirPathFiles[0].equals(filePathFiles[0])) {
			return file;		// return unchanged
		}

		// at this point we know the root is the same, now find how much is in common
		int i = 0;		// this will point at the first miscompare
		while ((i < dirPathFiles.length) && (i < filePathFiles.length)) {
			if (dirPathFiles[i].equals(filePathFiles[i])) {
				i++;
			} else {
				break;
			}
		}
		// save our current position
		int firstMismatch = i;

		// check whether the file is ABOVE the directory: ../..
		if (firstMismatch == filePathFiles.length) {
			return relativeParentFile(dirPathFiles.length - firstMismatch);
		}

		// build a new file from the path beyond the matching portions
		File diff = new File(filePathFiles[i].getName());
		while (++i < filePathFiles.length) {
			diff = new File(diff, filePathFiles[i].getName());
		}

		// check whether the file is BELOW the directory: subdir1/subdir2/file.ext
		if (firstMismatch == dirPathFiles.length) {
			return diff;
		}

		// the file must be a PEER of the directory: ../../subdir1/subdir2/file.ext
		return new File(relativeParentFile(dirPathFiles.length - firstMismatch), diff.getPath());
	}

	/**
	 * Return a file that is a re-specification of the specified
	 * file, relative to the current working directory.
	 *     Linux/Unix/Mac (CWD = /foo):
	 *         convertToRelativeFile(/foo/bar/baz.java)
	 *             => bar/baz.java
	 *     Windows (CWD = C:\foo):
	 *         convertToRelativeFile(C:\foo\bar\baz.java)
	 *             => bar/baz.java
	 * The file can be either a file or a directory.
	 * If the file is already relative or it cannot be made relative
	 * to the directory, it will be returned unchanged.
	 * 
	 * NB: This method has been tested on Windows and Linux,
	 * but not Mac (but the Mac is Unix-based these days, so
	 * it shouldn't be a problem...).
	 */
	public static File convertToRelativeFile(final File file) {
		return convertToRelativeFile(file, currentWorkingDirectory());
	}

	/**
	 * Return an array of files representing the path to the specified
	 * file. For example:
	 *     C:/foo/bar/baz.txt =>
	 *     { C:/, C:/foo, C:/foo/bar, C:/foo/bar/baz.txt }
	 */
	private static File[] pathFiles(File file) {
		List<File> path = new ArrayList<File>();
		for (File f = file; f != null; f = f.getParentFile()) {
			path.add(f);
		}
		Collections.reverse(path);
		return path.toArray(new File[path.size()]);
	}

	/**
	 * Return a file with the specified (non-zero) number of relative
	 * file names, e.g. xxx(3) => ../../..
	 */
	private static File relativeParentFile(int len) {
		if (len <= 0) {
			throw new IllegalArgumentException("length must be greater than zero: " + len);
		}
		File result = new File("..");
		for (int i = len - 1; i-- > 0; ) {
			result = new File(result, "..");
		}
		return result;
	}

	/**
	 * Return a file that is a re-specification of the specified
	 * file, absolute to the specified directory.
	 *     Linux/Unix/Mac:
	 *         convertToAbsoluteFile(bar/baz.java, /foo)
	 *             => /foo/bar/baz.java
	 *     Windows:
	 *         convertToAbsoluteFile(bar/baz.java, C:\foo)
	 *             => C:\foo\bar\baz.java
	 * The file can be either a file or a directory; the directory
	 * *should* be a directory.
	 * If the file is already absolute, it will be returned unchanged.
	 * 
	 * NB: This method has been tested on Windows and Linux,
	 * but not Mac (but the Mac is Unix-based these days, so
	 * it shouldn't be a problem...).
	 */
	public static File convertToAbsoluteFile(final File file, final File dir) {
		// check whether the file is already absolute
		if (file.isAbsolute()) {
			return file;		// return unchanged
		}
		return canonicalFile(new File(dir, file.getPath()));
	}

	/**
	 * Return a file that is a re-specification of the specified
	 * file, absolute to the current working directory.
	 *     Linux/Unix/Mac (CWD = /foo):
	 *         convertToAbsoluteFile(bar/baz.java)
	 *             => /foo/bar/baz.java
	 *     Windows (CWD = C:\foo):
	 *         convertToAbsoluteFile(bar/baz.java)
	 *             => C:\foo\bar\baz.java
	 * The file can be either a file or a directory.
	 * If the file is already absolute, it will be returned unchanged.
	 * 
	 * NB: This method has been tested on Windows and Linux,
	 * but not Mac (but the Mac is Unix-based these days, so
	 * it shouldn't be a problem...).
	 */
	public static File convertToAbsoluteFile(final File file) {
		return convertToAbsoluteFile(file, currentWorkingDirectory());
	}


	// ********** constructor **********

	/**
	 * Suppress default constructor, ensuring non-instantiability.
	 */
	private FileTools() {
		super();
		throw new UnsupportedOperationException();
	}

}

Back to the top