1 package org.apache.maven.shared.utils.io;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.maven.shared.utils.Os;
23 import org.apache.maven.shared.utils.StringUtils;
24
25 import javax.annotation.Nonnull;
26 import javax.annotation.Nullable;
27 import javax.annotation.WillClose;
28 import java.io.BufferedReader;
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.FileOutputStream;
32 import java.io.FileReader;
33 import java.io.FileWriter;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.InputStreamReader;
37 import java.io.OutputStream;
38 import java.io.OutputStreamWriter;
39 import java.io.Reader;
40 import java.io.Writer;
41 import java.net.URL;
42 import java.nio.channels.FileChannel;
43 import java.security.SecureRandom;
44 import java.text.DecimalFormat;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Collections;
48 import java.util.List;
49 import java.util.Random;
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 public class FileUtils
89 {
90 protected FileUtils()
91 {
92
93 }
94
95
96
97
98 private static final int ONE_KB = 1024;
99
100
101
102
103 private static final int ONE_MB = ONE_KB * ONE_KB;
104
105
106
107
108 private static final int ONE_GB = ONE_KB * ONE_MB;
109
110
111
112
113 private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 30;
114
115
116
117
118 private static final String FS = System.getProperty( "file.separator" );
119
120
121
122
123
124
125
126 private static final String[] INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME = { ":", "*", "?", "\"", "<", ">", "|" };
127
128
129
130
131
132 @Nonnull public static String[] getDefaultExcludes()
133 {
134 return DirectoryScanner.DEFAULTEXCLUDES;
135 }
136
137
138
139
140
141 @Nonnull public static List<String> getDefaultExcludesAsList()
142 {
143 return Arrays.asList( getDefaultExcludes() );
144 }
145
146
147
148
149
150
151 @Nonnull public static String getDefaultExcludesAsString()
152 {
153 return StringUtils.join( DirectoryScanner.DEFAULTEXCLUDES, "," );
154 }
155
156
157
158
159
160
161
162
163 @Nonnull public static String dirname( @Nonnull String filename )
164 {
165 int i = filename.lastIndexOf( File.separator );
166 return ( i >= 0 ? filename.substring( 0, i ) : "" );
167 }
168
169
170
171
172
173
174
175 @Nonnull public static String filename( @Nonnull String filename )
176 {
177 int i = filename.lastIndexOf( File.separator );
178 return ( i >= 0 ? filename.substring( i + 1 ) : filename );
179 }
180
181
182
183
184
185
186
187
188
189 @Nonnull public static String extension( @Nonnull String filename )
190 {
191
192 int lastSep = filename.lastIndexOf( File.separatorChar );
193 int lastDot;
194 if ( lastSep < 0 )
195 {
196 lastDot = filename.lastIndexOf( '.' );
197 }
198 else
199 {
200 lastDot = filename.substring( lastSep + 1 ).lastIndexOf( '.' );
201 if ( lastDot >= 0 )
202 {
203 lastDot += lastSep + 1;
204 }
205 }
206
207 if ( lastDot >= 0 && lastDot > lastSep )
208 {
209 return filename.substring( lastDot + 1 );
210 }
211
212 return "";
213 }
214
215
216
217
218
219
220
221 public static boolean fileExists( @Nonnull String fileName )
222 {
223 File file = new File( fileName );
224 return file.exists();
225 }
226
227
228
229
230
231
232
233
234 @Nonnull public static String fileRead( @Nonnull String file )
235 throws IOException
236 {
237 return fileRead( file, null );
238 }
239
240
241
242
243
244
245
246 @Nonnull private static String fileRead( @Nonnull String file, @Nullable String encoding )
247 throws IOException
248 {
249 return fileRead( new File( file ), encoding );
250 }
251
252
253
254
255
256
257
258
259 @Nonnull public static String fileRead( @Nonnull File file )
260 throws IOException
261 {
262 return fileRead( file, null );
263 }
264
265
266
267
268
269
270
271 @Nonnull public static String fileRead( @Nonnull File file, @Nullable String encoding )
272 throws IOException
273 {
274 StringBuilder buf = new StringBuilder();
275
276 Reader reader = null;
277
278 try
279 {
280 if ( encoding != null )
281 {
282 reader = new InputStreamReader( new FileInputStream( file ), encoding );
283 }
284 else
285 {
286 reader = new InputStreamReader( new FileInputStream( file ) );
287 }
288 int count;
289 char[] b = new char[512];
290 while ( ( count = reader.read( b ) ) > 0 )
291 {
292 buf.append( b, 0, count );
293 }
294 }
295 finally
296 {
297 IOUtil.close( reader );
298 }
299
300 return buf.toString();
301 }
302
303
304
305
306
307
308
309 @Nonnull public static String[] fileReadArray( @Nonnull File file )
310 throws IOException
311 {
312 List<String> files = loadFile( file );
313
314 return files.toArray( new String[files.size()] );
315 }
316
317
318
319
320
321
322
323
324
325 public static void fileAppend( @Nonnull String fileName, @Nonnull String data )
326 throws IOException
327 {
328 fileAppend( fileName, null, data );
329 }
330
331
332
333
334
335
336
337
338
339 public static void fileAppend( @Nonnull String fileName, @Nullable String encoding, @Nonnull String data )
340 throws IOException
341 {
342 FileOutputStream out = null;
343 try
344 {
345 out = new FileOutputStream( fileName, true );
346 if ( encoding != null )
347 {
348 out.write( data.getBytes( encoding ) );
349 }
350 else
351 {
352 out.write( data.getBytes() );
353 }
354 }
355 finally
356 {
357 IOUtil.close( out );
358 }
359 }
360
361
362
363
364
365
366
367
368
369 public static void fileWrite( @Nonnull String fileName, @Nonnull String data )
370 throws IOException
371 {
372 fileWrite( fileName, null, data );
373 }
374
375
376
377
378
379
380
381
382
383 public static void fileWrite( @Nonnull String fileName, @Nullable String encoding, @Nonnull String data )
384 throws IOException
385 {
386 File file = new File( fileName );
387 fileWrite( file, encoding, data );
388 }
389
390
391
392
393
394
395
396
397
398 public static void fileWrite( @Nonnull File file, @Nullable String encoding, @Nonnull String data )
399 throws IOException
400 {
401 Writer writer = null;
402 try
403 {
404 OutputStream out = new FileOutputStream( file );
405 if ( encoding != null )
406 {
407 writer = new OutputStreamWriter( out, encoding );
408 }
409 else
410 {
411 writer = new OutputStreamWriter( out );
412 }
413 writer.write( data );
414 }
415 finally
416 {
417 IOUtil.close( writer );
418 }
419 }
420
421
422
423
424
425
426
427
428
429 public static void fileWriteArray( @Nonnull File file, @Nullable String... data )
430 throws IOException
431 {
432 fileWriteArray( file, null, data );
433 }
434
435
436
437
438
439
440
441
442
443 public static void fileWriteArray( @Nonnull File file, @Nullable String encoding, @Nullable String... data )
444 throws IOException
445 {
446 Writer writer = null;
447 try
448 {
449 OutputStream out = new FileOutputStream( file );
450 if ( encoding != null )
451 {
452 writer = new OutputStreamWriter( out, encoding );
453 }
454 else
455 {
456 writer = new OutputStreamWriter( out );
457 }
458
459 for ( int i = 0; data != null && i < data.length; i++ )
460 {
461 writer.write( data[i] );
462 if ( i < data.length )
463 {
464 writer.write( "\n" );
465 }
466 }
467 }
468 finally
469 {
470 IOUtil.close( writer );
471 }
472 }
473
474
475
476
477
478
479 public static void fileDelete( @Nonnull String fileName )
480 {
481 File file = new File( fileName );
482
483 deleteLegacyStyle( file );
484 }
485
486
487
488
489
490
491
492
493
494
495
496
497
498 public static String[] getFilesFromExtension( @Nonnull String directory, @Nonnull String... extensions )
499 {
500 List<String> files = new ArrayList<String>();
501
502 File currentDir = new File( directory );
503
504 String[] unknownFiles = currentDir.list();
505
506 if ( unknownFiles == null )
507 {
508 return new String[0];
509 }
510
511 for ( String unknownFile : unknownFiles )
512 {
513 String currentFileName = directory + System.getProperty( "file.separator" ) + unknownFile;
514 File currentFile = new File( currentFileName );
515
516 if ( currentFile.isDirectory() )
517 {
518
519 if ( currentFile.getName().equals( "CVS" ) )
520 {
521 continue;
522 }
523
524
525
526
527 String[] fetchFiles = getFilesFromExtension( currentFileName, extensions );
528 files = blendFilesToList( files, fetchFiles );
529 }
530 else
531 {
532
533
534 String add = currentFile.getAbsolutePath();
535 if ( isValidFile( add, extensions ) )
536 {
537 files.add( add );
538 }
539 }
540 }
541
542
543 String[] foundFiles = new String[files.size()];
544 files.toArray( foundFiles );
545
546 return foundFiles;
547 }
548
549
550
551
552 @Nonnull private static List<String> blendFilesToList( @Nonnull List<String> v, @Nonnull String... files )
553 {
554 Collections.addAll( v, files );
555
556 return v;
557 }
558
559
560
561
562
563
564 private static boolean isValidFile( @Nonnull String file, @Nonnull String... extensions )
565 {
566 String extension = extension( file );
567
568
569
570
571 for ( String extension1 : extensions )
572 {
573 if ( extension1.equals( extension ) )
574 {
575 return true;
576 }
577 }
578
579 return false;
580
581 }
582
583
584
585
586
587
588
589
590 public static void mkdir( @Nonnull String dir )
591 {
592 File file = new File( dir );
593
594 if ( Os.isFamily( Os.FAMILY_WINDOWS ) && !isValidWindowsFileName( file ) )
595 {
596 throw new IllegalArgumentException(
597 "The file (" + dir + ") cannot contain any of the following characters: \n" + StringUtils.join(
598 INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME, " " ) );
599 }
600
601 if ( !file.exists() )
602 {
603
604 file.mkdirs();
605 }
606 }
607
608
609
610
611
612
613
614
615
616 public static boolean contentEquals( @Nonnull final File file1, @Nonnull final File file2 )
617 throws IOException
618 {
619 final boolean file1Exists = file1.exists();
620 if ( file1Exists != file2.exists() )
621 {
622 return false;
623 }
624
625 if ( !file1Exists )
626 {
627
628 return true;
629 }
630
631 if ( file1.isDirectory() || file2.isDirectory() )
632 {
633
634 return false;
635 }
636
637 InputStream input1 = null;
638 InputStream input2 = null;
639 try
640 {
641 input1 = new FileInputStream( file1 );
642 input2 = new FileInputStream( file2 );
643 return IOUtil.contentEquals( input1, input2 );
644
645 }
646 finally
647 {
648 IOUtil.close( input1 );
649 IOUtil.close( input2 );
650 }
651 }
652
653
654
655
656
657
658
659
660 public @Nullable static File toFile( final @Nullable URL url )
661 {
662 if ( url == null || !url.getProtocol().equalsIgnoreCase( "file" ) )
663 {
664 return null;
665 }
666
667 String filename = url.getFile().replace( '/', File.separatorChar );
668 int pos = -1;
669 while ( ( pos = filename.indexOf( '%', pos + 1 ) ) >= 0 )
670 {
671 if ( pos + 2 < filename.length() )
672 {
673 String hexStr = filename.substring( pos + 1, pos + 3 );
674 char ch = (char) Integer.parseInt( hexStr, 16 );
675 filename = filename.substring( 0, pos ) + ch + filename.substring( pos + 3 );
676 }
677 }
678 return new File( filename );
679 }
680
681
682
683
684
685
686
687
688 @Nonnull public static URL[] toURLs( @Nonnull final File... files )
689 throws IOException
690 {
691 final URL[] urls = new URL[files.length];
692
693 for ( int i = 0; i < urls.length; i++ )
694 {
695
696
697 urls[i] = files[i].toURL();
698 }
699
700 return urls;
701 }
702
703
704
705
706
707
708
709
710
711
712
713
714
715 @Nonnull public static String removeExtension( @Nonnull final String filename )
716 {
717 String ext = extension( filename );
718
719 if ( "".equals( ext ) )
720 {
721 return filename;
722 }
723
724 final int index = filename.lastIndexOf( ext ) - 1;
725 return filename.substring( 0, index );
726 }
727
728
729
730
731
732
733
734
735
736
737
738
739
740 @Nonnull public static String getExtension( @Nonnull final String filename )
741 {
742 return extension( filename );
743 }
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758 public static void copyFileToDirectory( @Nonnull final File source, @Nonnull final File destinationDirectory )
759 throws IOException
760 {
761 if ( destinationDirectory.exists() && !destinationDirectory.isDirectory() )
762 {
763 throw new IllegalArgumentException( "Destination is not a directory" );
764 }
765
766 copyFile( source, new File( destinationDirectory, source.getName() ) );
767 }
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783 private static void copyFileToDirectoryIfModified( @Nonnull final File source,
784 @Nonnull final File destinationDirectory )
785 throws IOException
786 {
787 if ( destinationDirectory.exists() && !destinationDirectory.isDirectory() )
788 {
789 throw new IllegalArgumentException( "Destination is not a directory" );
790 }
791
792 copyFileIfModified( source, new File( destinationDirectory, source.getName() ) );
793 }
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808 public static void copyFile( @Nonnull final File source, @Nonnull final File destination )
809 throws IOException
810 {
811
812 if ( !source.exists() )
813 {
814 final String message = "File " + source + " does not exist";
815 throw new IOException( message );
816 }
817 if ( Java7Support.isAtLeastJava7() && Java7Support.isSymLink( source ) )
818 {
819 File target = Java7Support.readSymbolicLink( source );
820 Java7Support.createSymbolicLink( destination, target );
821 return;
822 }
823
824
825 if ( source.getCanonicalPath().equals( destination.getCanonicalPath() ) )
826 {
827
828 return;
829 }
830
831 mkdirsFor( destination );
832
833 doCopyFile( source, destination );
834
835 if ( source.length() != destination.length() )
836 {
837 final String message = "Failed to copy full contents from " + source + " to " + destination;
838 throw new IOException( message );
839 }
840 }
841
842 private static void mkdirsFor( @Nonnull File destination )
843 {
844
845 if ( destination.getParentFile() != null && !destination.getParentFile().exists() )
846 {
847
848 destination.getParentFile().mkdirs();
849 }
850 }
851
852 private static void doCopyFile( @Nonnull File source, @Nonnull File destination )
853 throws IOException
854 {
855 FileInputStream fis = null;
856 FileOutputStream fos = null;
857 FileChannel input = null;
858 FileChannel output = null;
859 try
860 {
861 fis = new FileInputStream( source );
862 fos = new FileOutputStream( destination );
863 input = fis.getChannel();
864 output = fos.getChannel();
865 long size = input.size();
866 long pos = 0;
867 long count;
868 while ( pos < size )
869 {
870 count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
871 pos += output.transferFrom( input, pos, count );
872 }
873 }
874 finally
875 {
876 IOUtil.close( output );
877 IOUtil.close( fos );
878 IOUtil.close( input );
879 IOUtil.close( fis );
880 }
881 }
882
883
884
885
886
887
888
889
890
891
892
893
894
895 private static boolean copyFileIfModified( @Nonnull final File source, @Nonnull final File destination )
896 throws IOException
897 {
898 if ( destination.lastModified() < source.lastModified() )
899 {
900 copyFile( source, destination );
901
902 return true;
903 }
904
905 return false;
906 }
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923 public static void copyURLToFile( @Nonnull final URL source, @Nonnull final File destination )
924 throws IOException
925 {
926 copyStreamToFile( source.openStream(), destination );
927 }
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945 private static void copyStreamToFile( @Nonnull final @WillClose InputStream source,
946 @Nonnull final File destination )
947 throws IOException
948 {
949 FileOutputStream output = null;
950 try
951 {
952
953 if ( destination.getParentFile() != null && !destination.getParentFile().exists() )
954 {
955
956 destination.getParentFile().mkdirs();
957 }
958
959
960 if ( destination.exists() && !destination.canWrite() )
961 {
962 final String message = "Unable to open file " + destination + " for writing.";
963 throw new IOException( message );
964 }
965
966 output = new FileOutputStream( destination );
967 IOUtil.copy( source, output );
968 }
969 finally
970 {
971 IOUtil.close( source );
972 IOUtil.close( output );
973 }
974 }
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994 public static @Nonnull String normalize( @Nonnull final String path )
995 {
996 String normalized = path;
997
998 while ( true )
999 {
1000 int index = normalized.indexOf( "//" );
1001 if ( index < 0 )
1002 {
1003 break;
1004 }
1005 normalized = normalized.substring( 0, index ) + normalized.substring( index + 1 );
1006 }
1007
1008
1009 while ( true )
1010 {
1011 int index = normalized.indexOf( "/./" );
1012 if ( index < 0 )
1013 {
1014 break;
1015 }
1016 normalized = normalized.substring( 0, index ) + normalized.substring( index + 2 );
1017 }
1018
1019
1020 while ( true )
1021 {
1022 int index = normalized.indexOf( "/../" );
1023 if ( index < 0 )
1024 {
1025 break;
1026 }
1027 if ( index == 0 )
1028 {
1029 return null;
1030 }
1031 int index2 = normalized.lastIndexOf( '/', index - 1 );
1032 normalized = normalized.substring( 0, index2 ) + normalized.substring( index + 3 );
1033 }
1034
1035
1036 return normalized;
1037 }
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049 public static @Nonnull File resolveFile( final File baseFile, @Nonnull String filename )
1050 {
1051 String filenm = filename;
1052 if ( '/' != File.separatorChar )
1053 {
1054 filenm = filename.replace( '/', File.separatorChar );
1055 }
1056
1057 if ( '\\' != File.separatorChar )
1058 {
1059 filenm = filename.replace( '\\', File.separatorChar );
1060 }
1061
1062
1063 if ( filenm.startsWith( File.separator ) || ( Os.isFamily( Os.FAMILY_WINDOWS ) && filenm.indexOf( ":" ) > 0 ) )
1064 {
1065 File file = new File( filenm );
1066
1067 try
1068 {
1069 file = file.getCanonicalFile();
1070 }
1071 catch ( final IOException ioe )
1072 {
1073
1074 }
1075
1076 return file;
1077 }
1078
1079
1080 final char[] chars = filename.toCharArray();
1081 final StringBuilder sb = new StringBuilder();
1082
1083
1084
1085
1086 int start = 0;
1087 if ( '\\' == File.separatorChar )
1088 {
1089 sb.append( filenm.charAt( 0 ) );
1090 start++;
1091 }
1092
1093 for ( int i = start; i < chars.length; i++ )
1094 {
1095 final boolean doubleSeparator = File.separatorChar == chars[i] && File.separatorChar == chars[i - 1];
1096
1097 if ( !doubleSeparator )
1098 {
1099 sb.append( chars[i] );
1100 }
1101 }
1102
1103 filenm = sb.toString();
1104
1105
1106 File file = ( new File( baseFile, filenm ) ).getAbsoluteFile();
1107
1108 try
1109 {
1110 file = file.getCanonicalFile();
1111 }
1112 catch ( final IOException ioe )
1113 {
1114
1115 }
1116
1117 return file;
1118 }
1119
1120
1121
1122
1123
1124
1125
1126 public static void forceDelete( @Nonnull final String file )
1127 throws IOException
1128 {
1129 forceDelete( new File( file ) );
1130 }
1131
1132
1133
1134
1135
1136
1137
1138 public static void forceDelete( @Nonnull final File file )
1139 throws IOException
1140 {
1141 if ( file.isDirectory() )
1142 {
1143 deleteDirectory( file );
1144 }
1145 else
1146 {
1147
1148
1149
1150
1151 boolean filePresent = file.getCanonicalFile().exists();
1152 if ( !deleteFile( file ) && filePresent )
1153 {
1154 final String message = "File " + file + " unable to be deleted.";
1155 throw new IOException( message );
1156 }
1157 }
1158 }
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168 public static void delete( @Nonnull File file )
1169 throws IOException
1170 {
1171 if ( Java7Support.isAtLeastJava7() )
1172 {
1173 Java7Support.delete( file );
1174 }
1175 else
1176 {
1177 if ( !file.delete() )
1178 {
1179 throw new IOException( "Could not delete " + file.getName() );
1180 }
1181 }
1182 }
1183
1184 public static boolean deleteLegacyStyle( @Nonnull File file )
1185 {
1186 if ( Java7Support.isAtLeastJava7() )
1187 {
1188 try
1189 {
1190 Java7Support.delete( file );
1191 return true;
1192 }
1193 catch ( IOException e )
1194 {
1195 return false;
1196 }
1197 }
1198 else
1199 {
1200 return file.delete();
1201 }
1202 }
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212 private static boolean deleteFile( @Nonnull File file )
1213 throws IOException
1214 {
1215 if ( file.isDirectory() )
1216 {
1217 throw new IOException( "File " + file + " isn't a file." );
1218 }
1219
1220 if ( !deleteLegacyStyle( file ) )
1221 {
1222 if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
1223 {
1224 file = file.getCanonicalFile();
1225 System.gc();
1226 }
1227
1228 try
1229 {
1230 Thread.sleep( 10 );
1231 return deleteLegacyStyle( file );
1232 }
1233 catch ( InterruptedException ex )
1234 {
1235 return deleteLegacyStyle( file );
1236 }
1237 }
1238
1239 return true;
1240 }
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252 public static void forceMkdir( @Nonnull final File file )
1253 throws IOException
1254 {
1255 if ( Os.isFamily( Os.FAMILY_WINDOWS ) && !isValidWindowsFileName( file ) )
1256 {
1257 throw new IllegalArgumentException(
1258 "The file (" + file.getAbsolutePath() + ") cannot contain any of the following characters: \n"
1259 + StringUtils.join( INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME, " " ) );
1260 }
1261
1262 if ( file.exists() )
1263 {
1264 if ( file.isFile() )
1265 {
1266 final String message =
1267 "File " + file + " exists and is " + "not a directory. Unable to create directory.";
1268 throw new IOException( message );
1269 }
1270 }
1271 else
1272 {
1273 if ( !file.mkdirs() )
1274 {
1275 final String message = "Unable to create directory " + file;
1276 throw new IOException( message );
1277 }
1278 }
1279 }
1280
1281
1282
1283
1284
1285
1286
1287 public static void deleteDirectory( @Nonnull final String directory )
1288 throws IOException
1289 {
1290 deleteDirectory( new File( directory ) );
1291 }
1292
1293
1294
1295
1296
1297
1298
1299 public static void deleteDirectory( @Nonnull final File directory )
1300 throws IOException
1301 {
1302 if ( !directory.exists() )
1303 {
1304 return;
1305 }
1306
1307
1308
1309
1310 if ( deleteLegacyStyle( directory ) )
1311 {
1312 return;
1313 }
1314
1315 cleanDirectory( directory );
1316 if ( !deleteLegacyStyle( directory ) )
1317 {
1318 final String message = "Directory " + directory + " unable to be deleted.";
1319 throw new IOException( message );
1320 }
1321 }
1322
1323
1324
1325
1326
1327
1328
1329 public static void cleanDirectory( @Nonnull final File directory )
1330 throws IOException
1331 {
1332 if ( !directory.exists() )
1333 {
1334 final String message = directory + " does not exist";
1335 throw new IllegalArgumentException( message );
1336 }
1337
1338 if ( !directory.isDirectory() )
1339 {
1340 final String message = directory + " is not a directory";
1341 throw new IllegalArgumentException( message );
1342 }
1343
1344 IOException exception = null;
1345
1346 final File[] files = directory.listFiles();
1347
1348 if ( files == null )
1349 {
1350 return;
1351 }
1352
1353 for ( final File file : files )
1354 {
1355 try
1356 {
1357 forceDelete( file );
1358 }
1359 catch ( final IOException ioe )
1360 {
1361 exception = ioe;
1362 }
1363 }
1364
1365 if ( null != exception )
1366 {
1367 throw exception;
1368 }
1369 }
1370
1371
1372
1373
1374
1375
1376
1377 public static long sizeOfDirectory( @Nonnull final String directory )
1378 {
1379 return sizeOfDirectory( new File( directory ) );
1380 }
1381
1382
1383
1384
1385
1386
1387
1388 public static long sizeOfDirectory( @Nonnull final File directory )
1389 {
1390 if ( !directory.exists() )
1391 {
1392 final String message = directory + " does not exist";
1393 throw new IllegalArgumentException( message );
1394 }
1395
1396 if ( !directory.isDirectory() )
1397 {
1398 final String message = directory + " is not a directory";
1399 throw new IllegalArgumentException( message );
1400 }
1401
1402 long size = 0;
1403
1404 final File[] files = directory.listFiles();
1405 if ( files == null )
1406 {
1407 throw new IllegalArgumentException( "Problems reading directory" );
1408 }
1409
1410 for ( final File file : files )
1411 {
1412 if ( file.isDirectory() )
1413 {
1414 size += sizeOfDirectory( file );
1415 }
1416 else
1417 {
1418 size += file.length();
1419 }
1420 }
1421
1422 return size;
1423 }
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436 @Nonnull
1437 public static List<File> getFiles( @Nonnull File directory, @Nullable String includes, @Nullable String excludes )
1438 throws IOException
1439 {
1440 return getFiles( directory, includes, excludes, true );
1441 }
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454 @Nonnull
1455 public static List<File> getFiles( @Nonnull File directory, @Nullable String includes, @Nullable String excludes,
1456 boolean includeBasedir )
1457 throws IOException
1458 {
1459 List<String> fileNames = getFileNames( directory, includes, excludes, includeBasedir );
1460
1461 List<File> files = new ArrayList<File>();
1462
1463 for ( String filename : fileNames )
1464 {
1465 files.add( new File( filename ) );
1466 }
1467
1468 return files;
1469 }
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482 @Nonnull public static List<String> getFileNames( @Nonnull File directory, @Nullable String includes,
1483 @Nullable String excludes, boolean includeBasedir )
1484 throws IOException
1485 {
1486 return getFileNames( directory, includes, excludes, includeBasedir, true );
1487 }
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500 @Nonnull private static List<String> getFileNames( @Nonnull File directory, @Nullable String includes,
1501 @Nullable String excludes, boolean includeBasedir,
1502 boolean isCaseSensitive )
1503 throws IOException
1504 {
1505 return getFileAndDirectoryNames( directory, includes, excludes, includeBasedir, isCaseSensitive, true, false );
1506 }
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519 @Nonnull public static List<String> getDirectoryNames( @Nonnull File directory, @Nullable String includes,
1520 @Nullable String excludes, boolean includeBasedir )
1521 throws IOException
1522 {
1523 return getDirectoryNames( directory, includes, excludes, includeBasedir, true );
1524 }
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537 @Nonnull public static List<String> getDirectoryNames( @Nonnull File directory, @Nullable String includes,
1538 @Nullable String excludes, boolean includeBasedir,
1539 boolean isCaseSensitive )
1540 throws IOException
1541 {
1542 return getFileAndDirectoryNames( directory, includes, excludes, includeBasedir, isCaseSensitive, false, true );
1543 }
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557 @Nonnull public static List<String> getFileAndDirectoryNames( File directory, @Nullable String includes,
1558 @Nullable String excludes, boolean includeBasedir,
1559 boolean isCaseSensitive, boolean getFiles,
1560 boolean getDirectories )
1561 {
1562 DirectoryScanner scanner = new DirectoryScanner();
1563
1564 scanner.setBasedir( directory );
1565
1566 if ( includes != null )
1567 {
1568 scanner.setIncludes( StringUtils.split( includes, "," ) );
1569 }
1570
1571 if ( excludes != null )
1572 {
1573 scanner.setExcludes( StringUtils.split( excludes, "," ) );
1574 }
1575
1576 scanner.setCaseSensitive( isCaseSensitive );
1577
1578 scanner.scan();
1579
1580 List<String> list = new ArrayList<String>();
1581
1582 if ( getFiles )
1583 {
1584 String[] files = scanner.getIncludedFiles();
1585
1586 for ( String file : files )
1587 {
1588 if ( includeBasedir )
1589 {
1590 list.add( directory + FileUtils.FS + file );
1591 }
1592 else
1593 {
1594 list.add( file );
1595 }
1596 }
1597 }
1598
1599 if ( getDirectories )
1600 {
1601 String[] directories = scanner.getIncludedDirectories();
1602
1603 for ( String directory1 : directories )
1604 {
1605 if ( includeBasedir )
1606 {
1607 list.add( directory + FileUtils.FS + directory1 );
1608 }
1609 else
1610 {
1611 list.add( directory1 );
1612 }
1613 }
1614 }
1615
1616 return list;
1617 }
1618
1619
1620
1621
1622
1623
1624
1625
1626 public static void copyDirectory( @Nonnull File sourceDirectory, @Nonnull File destinationDirectory )
1627 throws IOException
1628 {
1629 copyDirectory( sourceDirectory, destinationDirectory, "**", null );
1630 }
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642 public static void copyDirectory( @Nonnull File sourceDirectory, @Nonnull File destinationDirectory,
1643 @Nullable String includes, @Nullable String excludes )
1644 throws IOException
1645 {
1646 if ( !sourceDirectory.exists() )
1647 {
1648 return;
1649 }
1650
1651 List<File> files = getFiles( sourceDirectory, includes, excludes );
1652
1653 for ( File file : files )
1654 {
1655 copyFileToDirectory( file, destinationDirectory );
1656 }
1657 }
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672 public static void copyDirectoryStructure( @Nonnull File sourceDirectory, @Nonnull File destinationDirectory )
1673 throws IOException
1674 {
1675 copyDirectoryStructure( sourceDirectory, destinationDirectory, destinationDirectory, false );
1676 }
1677
1678 private static void copyDirectoryStructure( @Nonnull File sourceDirectory, @Nonnull File destinationDirectory,
1679 File rootDestinationDirectory, boolean onlyModifiedFiles )
1680 throws IOException
1681 {
1682
1683 if ( sourceDirectory == null )
1684 {
1685 throw new IOException( "source directory can't be null." );
1686 }
1687
1688
1689 if ( destinationDirectory == null )
1690 {
1691 throw new IOException( "destination directory can't be null." );
1692 }
1693
1694 if ( sourceDirectory.equals( destinationDirectory ) )
1695 {
1696 throw new IOException( "source and destination are the same directory." );
1697 }
1698
1699 if ( !sourceDirectory.exists() )
1700 {
1701 throw new IOException( "Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")." );
1702 }
1703
1704 File[] files = sourceDirectory.listFiles();
1705
1706 if ( files == null )
1707 {
1708 return;
1709 }
1710
1711 String sourcePath = sourceDirectory.getAbsolutePath();
1712
1713 for ( File file : files )
1714 {
1715 if ( file.equals( rootDestinationDirectory ) )
1716 {
1717
1718 continue;
1719 }
1720
1721 String dest = file.getAbsolutePath();
1722
1723 dest = dest.substring( sourcePath.length() + 1 );
1724
1725 File destination = new File( destinationDirectory, dest );
1726
1727 if ( file.isFile() )
1728 {
1729 destination = destination.getParentFile();
1730
1731 if ( onlyModifiedFiles )
1732 {
1733 copyFileToDirectoryIfModified( file, destination );
1734 }
1735 else
1736 {
1737 copyFileToDirectory( file, destination );
1738 }
1739 }
1740 else if ( file.isDirectory() )
1741 {
1742 if ( !destination.exists() && !destination.mkdirs() )
1743 {
1744 throw new IOException(
1745 "Could not create destination directory '" + destination.getAbsolutePath() + "'." );
1746 }
1747
1748 copyDirectoryStructure( file, destination, rootDestinationDirectory, onlyModifiedFiles );
1749 }
1750 else
1751 {
1752 throw new IOException( "Unknown file type: " + file.getAbsolutePath() );
1753 }
1754 }
1755 }
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770 public static void rename( @Nonnull File from, @Nonnull File to )
1771 throws IOException
1772 {
1773 if ( to.exists() && !deleteLegacyStyle( to ) )
1774 {
1775 throw new IOException( "Failed to delete " + to + " while trying to rename " + from );
1776 }
1777
1778 File parent = to.getParentFile();
1779 if ( parent != null && !parent.exists() && !parent.mkdirs() )
1780 {
1781 throw new IOException( "Failed to create directory " + parent + " while trying to rename " + from );
1782 }
1783
1784 if ( !from.renameTo( to ) )
1785 {
1786 copyFile( from, to );
1787 if ( !deleteLegacyStyle( from ) )
1788 {
1789 throw new IOException( "Failed to delete " + from + " while trying to rename it." );
1790 }
1791 }
1792 }
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817 public static File createTempFile( @Nonnull String prefix, @Nonnull String suffix, @Nullable File parentDir )
1818 {
1819 File result;
1820 String parent = System.getProperty( "java.io.tmpdir" );
1821 if ( parentDir != null )
1822 {
1823 parent = parentDir.getPath();
1824 }
1825 DecimalFormat fmt = new DecimalFormat( "#####" );
1826 SecureRandom secureRandom = new SecureRandom();
1827 long secureInitializer = secureRandom.nextLong();
1828 Random rand = new Random( secureInitializer + Runtime.getRuntime().freeMemory() );
1829 do
1830 {
1831 result = new File( parent, prefix + fmt.format( positiveRandom( rand ) ) + suffix );
1832 }
1833 while ( result.exists() );
1834
1835 return result;
1836 }
1837
1838 private static int positiveRandom( Random rand )
1839 {
1840 int a = rand.nextInt();
1841 while ( a == Integer.MIN_VALUE )
1842 {
1843 a = rand.nextInt();
1844 }
1845 return Math.abs( a );
1846 }
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857 public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable String encoding,
1858 @Nullable FilterWrapper... wrappers )
1859 throws IOException
1860 {
1861 copyFile( from, to, encoding, wrappers, false );
1862 }
1863
1864
1865
1866
1867 public abstract static class FilterWrapper
1868 {
1869 public abstract Reader getReader( Reader fileReader );
1870 }
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884 public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable String encoding,
1885 @Nullable FilterWrapper[] wrappers, boolean overwrite )
1886 throws IOException
1887 {
1888 if ( wrappers != null && wrappers.length > 0 )
1889 {
1890
1891 Reader fileReader = null;
1892 Writer fileWriter = null;
1893 try
1894 {
1895 if ( encoding == null || encoding.length() < 1 )
1896 {
1897 fileReader = new BufferedReader( new FileReader( from ) );
1898 fileWriter = new FileWriter( to );
1899 }
1900 else
1901 {
1902 FileInputStream instream = new FileInputStream( from );
1903
1904 FileOutputStream outstream = new FileOutputStream( to );
1905
1906 fileReader = new BufferedReader( new InputStreamReader( instream, encoding ) );
1907
1908 fileWriter = new OutputStreamWriter( outstream, encoding );
1909 }
1910
1911 Reader reader = fileReader;
1912 for ( FilterWrapper wrapper : wrappers )
1913 {
1914 reader = wrapper.getReader( reader );
1915 }
1916
1917 IOUtil.copy( reader, fileWriter );
1918 }
1919 finally
1920 {
1921 IOUtil.close( fileReader );
1922 IOUtil.close( fileWriter );
1923 }
1924 }
1925 else
1926 {
1927 if ( to.lastModified() < from.lastModified() || overwrite )
1928 {
1929 copyFile( from, to );
1930 }
1931 }
1932 }
1933
1934
1935
1936
1937
1938
1939
1940
1941 @Nonnull public static List<String> loadFile( @Nonnull File file )
1942 throws IOException
1943 {
1944 List<String> lines = new ArrayList<String>();
1945
1946 if ( file.exists() )
1947 {
1948 FileReader fileReader = new FileReader( file );
1949 try
1950 {
1951 BufferedReader reader = new BufferedReader( fileReader );
1952
1953 String line = reader.readLine();
1954
1955 while ( line != null )
1956 {
1957 line = line.trim();
1958
1959 if ( !line.startsWith( "#" ) && line.length() != 0 )
1960 {
1961 lines.add( line );
1962 }
1963 line = reader.readLine();
1964 }
1965
1966 reader.close();
1967 }
1968 finally
1969 {
1970 fileReader.close();
1971 }
1972 }
1973
1974 return lines;
1975 }
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986 private static boolean isValidWindowsFileName( @Nonnull File f )
1987 {
1988 if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
1989 {
1990 if ( StringUtils.indexOfAny( f.getName(), INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME ) != -1 )
1991 {
1992 return false;
1993 }
1994
1995 if ( f.getParentFile() != null )
1996 {
1997 return isValidWindowsFileName( f.getParentFile() );
1998 }
1999 }
2000
2001 return true;
2002 }
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017 public static boolean isSymbolicLink( final @Nonnull File file )
2018 throws IOException
2019 {
2020 if ( Java7Support.isAtLeastJava7() )
2021 {
2022 return Java7Support.isSymLink( file );
2023 }
2024 return isSymbolicLinkLegacy( file );
2025 }
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035 public static boolean isSymbolicLinkForSure( final @Nonnull File file )
2036 throws IOException
2037 {
2038 return Java7Support.isAtLeastJava7() && Java7Support.isSymLink( file );
2039 }
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059 static boolean isSymbolicLinkLegacy( final @Nonnull File file )
2060 throws IOException
2061 {
2062 final File canonical = new File( file.getCanonicalPath() );
2063 return !file.getAbsolutePath().equals( canonical.getPath() );
2064 }
2065
2066 }