/
IO.java
1820 lines (1580 loc) · 49.3 KB
/
IO.java
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
package aQute.lib.io;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.Closeable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.EOFException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.UTFDataFormatException;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.security.MessageDigest;
import java.text.CollationKey;
import java.text.Collator;
import java.util.Collection;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import aQute.bnd.exceptions.ConsumerWithException;
import aQute.lib.stringrover.StringRover;
import aQute.libg.glob.Glob;
public class IO {
private static final Pattern WINDOWS_MACROS = Pattern.compile("%([^%]+)%");
private static final int BUFFER_SIZE = IOConstants.PAGE_SIZE * 16;
private static final int DIRECT_MAP_THRESHOLD = BUFFER_SIZE;
private static final boolean isWindows = File.separatorChar == '\\';
static final public File work = new File(
System.getProperty("user.dir"));
static final public File home;
static final public File JAVA_HOME;
private static final EnumSet<StandardOpenOption> writeOptions = EnumSet.of(StandardOpenOption.WRITE,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
private static final EnumSet<StandardOpenOption> readOptions = EnumSet.of(StandardOpenOption.READ);
static {
EnvironmentCalculator hc = new EnvironmentCalculator(isWindows);
home = hc.getHome();
JAVA_HOME = hc.getJavaHome();
}
public static String getExtension(String fileName, String deflt) {
int n = fileName.lastIndexOf('.');
if (n < 0)
return deflt;
return fileName.substring(n + 1);
}
public static Collection<File> tree(File current) {
Set<File> files = new LinkedHashSet<>();
traverse(files, current, null);
return files;
}
public static Collection<File> tree(File current, String glob) {
Set<File> files = new LinkedHashSet<>();
traverse(files, current, glob == null ? null : new Glob(glob));
return files;
}
private static void traverse(Collection<File> files, File current, Glob glob) {
if (current.isFile() && (glob == null || glob.matcher(current.getName())
.matches())) {
files.add(current);
} else if (current.isDirectory()) {
for (File sub : listFiles(current)) {
traverse(files, sub, glob);
}
}
}
public static Collator fileCollator() {
Collator collator = Collator.getInstance(Locale.ROOT);
collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
collator.setStrength(Collator.IDENTICAL); // case-sensitive
return collator;
}
public static <FILE> Comparator<FILE> fileComparator(Function<? super FILE, ? extends String> keyExtractor) {
return Comparator.comparing(keyExtractor, fileCollator()::compare);
}
public static Stream<String> listStream(File dir, BiPredicate<? super File, ? super String> filter) {
if ((dir != null) && dir.isDirectory()) {
String[] names = dir.list();
if (names != null) {
Stream<String> result = StreamSupport
.stream(Spliterators.<String> spliterator(names,
Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.DISTINCT), false)
.filter(name -> filter.test(dir, name))
.map(fileCollator()::getCollationKey)
.sorted()
.map(CollationKey::getSourceString);
return result;
}
}
return Stream.empty();
}
public static Stream<String> listStream(File dir) {
return listStream(dir, (d, n) -> true);
}
public static List<String> list(File dir, BiPredicate<? super File, ? super String> filter) {
try (Stream<String> stream = listStream(dir, filter)) {
return stream.collect(toList());
}
}
public static List<String> list(File dir) {
return list(dir, (d, n) -> true);
}
public static List<File> listFiles(File dir, BiPredicate<? super File, ? super String> filter) {
try (Stream<String> stream = listStream(dir, filter)) {
return stream.map(name -> new File(dir, name))
.collect(toList());
}
}
public static List<File> listFiles(File dir) {
return listFiles(dir, (d, n) -> true);
}
public static Stream<String> listStream(Path dir, Predicate<? super Path> filter) {
if ((dir != null) && Files.isDirectory(dir)) {
try {
Stream<String> result = Files.list(dir)
.filter(filter)
.map(Path::getFileName)
.map(Path::toString)
.map(fileCollator()::getCollationKey)
.sorted()
.map(CollationKey::getSourceString);
return result;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return Stream.empty();
}
public static Stream<String> listStream(Path dir, BiPredicate<? super Path, ? super String> filter) {
if ((dir != null) && Files.isDirectory(dir)) {
try {
Stream<String> result = Files.list(dir)
.map(Path::getFileName)
.map(Path::toString)
.filter(name -> filter.test(dir, name))
.map(fileCollator()::getCollationKey)
.sorted()
.map(CollationKey::getSourceString);
return result;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return Stream.empty();
}
public static Stream<String> listStream(Path dir) {
return listStream(dir, p -> true);
}
public static List<String> list(Path dir, Predicate<? super Path> filter) {
try (Stream<String> stream = listStream(dir, filter)) {
return stream.collect(toList());
}
}
public static List<String> list(Path dir, BiPredicate<? super Path, ? super String> filter) {
try (Stream<String> stream = listStream(dir, filter)) {
return stream.collect(toList());
}
}
public static List<String> list(Path dir) {
return list(dir, p -> true);
}
public static List<Path> listPaths(Path dir, Predicate<? super Path> filter) {
try (Stream<String> stream = listStream(dir, filter)) {
return stream.map(name -> dir.resolve(name))
.collect(toList());
}
}
public static List<Path> listPaths(Path dir, BiPredicate<? super Path, ? super String> filter) {
try (Stream<String> stream = listStream(dir, filter)) {
return stream.map(name -> dir.resolve(name))
.collect(toList());
}
}
public static List<Path> listPaths(Path dir) {
return listPaths(dir, p -> true);
}
public static File copy(byte[] data, File file) throws IOException {
copy(data, file.toPath());
return file;
}
public static Path copy(byte[] data, Path path) throws IOException {
try (FileChannel out = writeChannel(path)) {
ByteBuffer bb = ByteBuffer.wrap(data);
while (bb.hasRemaining()) {
out.write(bb);
}
}
return path;
}
public static Writer copy(byte[] data, Writer w) throws IOException {
w.write(new String(data, 0, data.length, UTF_8));
return w;
}
public static OutputStream copy(byte[] data, OutputStream out) throws IOException {
out.write(data, 0, data.length);
return out;
}
public static Writer copy(Reader r, Writer w) throws IOException {
try {
char[] buffer = new char[BUFFER_SIZE];
for (int size; (size = r.read(buffer, 0, buffer.length)) > 0;) {
w.write(buffer, 0, size);
}
return w;
} finally {
r.close();
}
}
public static OutputStream copy(Reader r, OutputStream out) throws IOException {
return copy(r, out, UTF_8);
}
public static OutputStream copy(Reader r, OutputStream out, String charset) throws IOException {
return copy(r, out, Charset.forName(charset));
}
public static OutputStream copy(Reader r, OutputStream out, Charset charset) throws IOException {
Writer w = writer(out, charset);
try {
copy(r, w);
return out;
} finally {
w.flush();
}
}
public static Writer copy(InputStream in, Writer w) throws IOException {
return copy(in, w, UTF_8);
}
public static Writer copy(InputStream in, Writer w, String charset) throws IOException {
return copy(in, w, Charset.forName(charset));
}
public static Writer copy(InputStream in, Writer w, Charset charset) throws IOException {
return copy(reader(in, charset), w);
}
/**
* If InputStream throws EOFException, map it to returning -1. Other
* IOExceptions are propagated.
*/
private static int read(InputStream in, byte[] b, int off, int len) throws IOException {
try {
return in.read(b, off, len);
} catch (EOFException e) {
return -1;
}
}
/**
* If ReadableByteChannel throws EOFException, map it to returning -1. Other
* IOExceptions are propagated.
*/
private static int read(ReadableByteChannel in, ByteBuffer bb) throws IOException {
try {
return in.read(bb);
} catch (EOFException e) {
return -1;
}
}
public static OutputStream copy(InputStream in, OutputStream out) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
for (int size; (size = read(in, buffer, 0, buffer.length)) > 0;) {
out.write(buffer, 0, size);
}
return out;
} finally {
in.close();
}
}
public static OutputStream copy(InputStream in, OutputStream out, int limit) throws IOException {
return copy(new LimitedInputStream(in, limit), out);
}
public static ByteBufferOutputStream copy(InputStream in, ByteBufferOutputStream out) throws IOException {
try {
out.write(in);
return out;
} finally {
in.close();
}
}
public static DataOutput copy(InputStream in, DataOutput out) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
for (int size; (size = read(in, buffer, 0, buffer.length)) > 0;) {
out.write(buffer, 0, size);
}
return out;
} finally {
in.close();
}
}
public static WritableByteChannel copy(ReadableByteChannel in, WritableByteChannel out) throws IOException {
try {
ByteBuffer bb = ByteBuffer.allocateDirect(BUFFER_SIZE);
while (read(in, bb) > 0) {
bb.flip();
out.write(bb);
bb.compact();
}
for (bb.flip(); bb.hasRemaining();) {
out.write(bb);
}
return out;
} finally {
in.close();
}
}
public static ByteBuffer copy(InputStream in, ByteBuffer bb) throws IOException {
try {
if (bb.hasArray()) {
byte[] buffer = bb.array();
int offset = bb.arrayOffset();
for (int size, position; bb.hasRemaining()
&& (size = read(in, buffer, offset + (position = bb.position()), bb.remaining())) > 0;) {
bb.position(position + size);
}
} else {
int length = Math.min(bb.remaining(), BUFFER_SIZE);
byte[] buffer = new byte[length];
for (int size; length > 0 && (size = read(in, buffer, 0, length)) > 0;) {
bb.put(buffer, 0, size);
length = Math.min(bb.remaining(), buffer.length);
}
}
return bb;
} finally {
in.close();
}
}
public static byte[] copy(InputStream in, byte[] data) throws IOException {
return copy(in, data, 0, data.length);
}
public static byte[] copy(InputStream in, byte[] data, int off, int len) throws IOException {
try {
for (int remaining, size; (remaining = len - off) > 0 && (size = read(in, data, off, remaining)) > 0;) {
off += size;
}
return data;
} finally {
in.close();
}
}
public static OutputStream copy(ByteBuffer bb, OutputStream out) throws IOException {
if (out instanceof ByteBufferOutputStream) {
ByteBufferOutputStream bbout = (ByteBufferOutputStream) out;
bbout.write(bb);
} else if (bb.hasArray()) {
out.write(bb.array(), bb.arrayOffset() + bb.position(), bb.remaining());
bb.position(bb.limit());
} else {
int length = Math.min(bb.remaining(), BUFFER_SIZE);
byte[] buffer = new byte[length];
while (length > 0) {
bb.get(buffer, 0, length);
out.write(buffer, 0, length);
length = Math.min(bb.remaining(), buffer.length);
}
}
return out;
}
public static DataOutput copy(ByteBuffer bb, DataOutput out) throws IOException {
if (out instanceof ByteBufferDataOutput) {
ByteBufferDataOutput bbout = (ByteBufferDataOutput) out;
bbout.write(bb);
} else if (bb.hasArray()) {
out.write(bb.array(), bb.arrayOffset() + bb.position(), bb.remaining());
bb.position(bb.limit());
} else {
int length = Math.min(bb.remaining(), BUFFER_SIZE);
byte[] buffer = new byte[length];
while (length > 0) {
bb.get(buffer, 0, length);
out.write(buffer, 0, length);
length = Math.min(bb.remaining(), buffer.length);
}
}
return out;
}
public static MessageDigest copy(URL url, MessageDigest md) throws IOException {
return copy(stream(url), md);
}
public static MessageDigest copy(File file, MessageDigest md) throws IOException {
return copy(file.toPath(), md);
}
public static MessageDigest copy(Path path, MessageDigest md) throws IOException {
return copy(readChannel(path), md);
}
public static MessageDigest copy(URLConnection conn, MessageDigest md) throws IOException {
return copy(conn.getInputStream(), md);
}
public static MessageDigest copy(InputStream in, MessageDigest md) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
for (int size; (size = read(in, buffer, 0, buffer.length)) > 0;) {
md.update(buffer, 0, size);
}
return md;
} finally {
in.close();
}
}
public static MessageDigest copy(ReadableByteChannel in, MessageDigest md) throws IOException {
try {
ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE);
while (read(in, bb) > 0) {
bb.flip();
md.update(bb);
bb.compact();
}
for (bb.flip(); bb.hasRemaining();) {
md.update(bb);
}
return md;
} finally {
in.close();
}
}
public static File copy(URL url, File file) throws IOException {
return copy(stream(url), file);
}
public static File copy(URLConnection conn, File file) throws IOException {
return copy(conn.getInputStream(), file);
}
public static URL copy(InputStream in, URL url) throws IOException {
return copy(in, url, null);
}
public static URL copy(InputStream in, URL url, String method) throws IOException {
URLConnection c = url.openConnection();
HttpURLConnection http = (c instanceof HttpURLConnection) ? (HttpURLConnection) c : null;
if (http != null && method != null) {
http.setRequestMethod(method);
}
c.setDoOutput(true);
try (OutputStream out = c.getOutputStream()) {
copy(in, out);
return url;
} finally {
if (http != null) {
http.disconnect();
}
}
}
public static File copy(File src, File tgt) throws IOException {
copy(src.toPath(), tgt.toPath());
return tgt;
}
public static Path copy(Path src, Path tgt) throws IOException {
final Path source = src.toAbsolutePath();
final Path target = tgt.toAbsolutePath();
if (Files.isRegularFile(source)) {
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
return tgt;
}
if (Files.isDirectory(source)) {
if (Files.notExists(target)) {
mkdirs(target);
}
if (!Files.isDirectory(target))
throw new IllegalArgumentException("target directory for a directory must be a directory: " + target);
if (target.startsWith(source))
throw new IllegalArgumentException("target directory can not be child of source directory.");
Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
new FileVisitor<Path>() {
final FileTime now = FileTime.fromMillis(System.currentTimeMillis());
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path targetdir = target.resolve(source.relativize(dir));
try {
Files.copy(dir, targetdir);
} catch (FileAlreadyExistsException e) {
if (!Files.isDirectory(targetdir))
throw e;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path targetFile = target.resolve(source.relativize(file));
Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING);
Files.setLastModifiedTime(targetFile, now);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
if (exc != null) { // directory iteration failed
throw exc;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null) {
throw exc;
}
return FileVisitResult.CONTINUE;
}
});
return tgt;
}
throw new FileNotFoundException("During copy: " + source.toString());
}
public static File copy(InputStream in, File file) throws IOException {
copy(in, file.toPath());
return file;
}
public static Path copy(InputStream in, Path path) throws IOException {
try (FileChannel out = writeChannel(path)) {
copy(in, out);
}
return path;
}
public static OutputStream copy(File file, OutputStream out) throws IOException {
return copy(file.toPath(), out);
}
public static OutputStream copy(Path path, OutputStream out) throws IOException {
return copy(readChannel(path), out);
}
public static WritableByteChannel copy(InputStream in, WritableByteChannel out) throws IOException {
try {
ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE);
byte[] buffer = bb.array();
for (int size, position; (size = read(in, buffer, position = bb.position(), bb.remaining())) > 0;) {
bb.position(position + size);
bb.flip();
out.write(bb);
bb.compact();
}
for (bb.flip(); bb.hasRemaining();) {
out.write(bb);
}
return out;
} finally {
in.close();
}
}
public static OutputStream copy(ReadableByteChannel in, OutputStream out) throws IOException {
try {
ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE);
byte[] buffer = bb.array();
for (; read(in, bb) > 0; bb.clear()) {
out.write(buffer, 0, bb.position());
}
return out;
} finally {
in.close();
}
}
public static byte[] read(File file) throws IOException {
try (FileChannel in = readChannel(file.toPath())) {
ByteBuffer bb = ByteBuffer.allocate((int) in.size());
while (read(in, bb) > 0) {}
return bb.array();
}
}
public static ByteBuffer read(Path path) throws IOException {
try (FileChannel in = readChannel(path)) {
long size = in.size();
if (!isWindows && (size > DIRECT_MAP_THRESHOLD)) {
return in.map(MapMode.READ_ONLY, 0, size);
}
ByteBuffer bb = ByteBuffer.allocate((int) size);
while (read(in, bb) > 0) {}
bb.flip();
return bb;
}
}
public static byte[] read(ByteBuffer bb) {
byte[] data = new byte[bb.remaining()];
bb.get(data, 0, data.length);
return data;
}
public static byte[] read(URL url) throws IOException {
URLConnection conn = url.openConnection();
conn.connect();
int length = conn.getContentLength();
if (length == -1) {
return read(conn.getInputStream());
}
return copy(conn.getInputStream(), new byte[length]);
}
public static byte[] read(InputStream in) throws IOException {
return copy(in, new ByteBufferOutputStream()).toByteArray();
}
public static void write(byte[] data, OutputStream out) throws IOException {
copy(data, out);
}
public static void write(byte[] data, File file) throws IOException {
copy(data, file);
}
public static String collect(File file) throws IOException {
return collect(file.toPath(), UTF_8);
}
public static String collect(File file, String encoding) throws IOException {
return collect(file.toPath(), Charset.forName(encoding));
}
public static String collect(File file, Charset encoding) throws IOException {
return collect(file.toPath(), encoding);
}
public static String collect(Path path) throws IOException {
return collect(path, UTF_8);
}
public static String collect(Path path, Charset encoding) throws IOException {
return collect(reader(path, encoding));
}
public static String collect(ByteBuffer bb, Charset encoding) {
return decode(bb, encoding).toString();
}
public static String collect(URL url, String encoding) throws IOException {
return collect(stream(url), Charset.forName(encoding));
}
public static String collect(URL url, Charset encoding) throws IOException {
return collect(stream(url), encoding);
}
public static String collect(URL url) throws IOException {
return collect(url, UTF_8);
}
public static String collect(String path) throws IOException {
return collect(Paths.get(path), UTF_8);
}
public static String collect(InputStream in) throws IOException {
return collect(in, UTF_8);
}
public static String collect(InputStream in, String encoding) throws IOException {
return collect(in, Charset.forName(encoding));
}
public static String collect(InputStream in, Charset encoding) throws IOException {
return collect(reader(in, encoding));
}
public static String collect(Reader r) throws IOException {
return copy(r, new CharArrayWriter()).toString();
}
/**
* Create a temporary file.
*
* @param directory the directory in which to create the file. Can be null,
* in which case the system TMP directory is used
* @param pattern the filename prefix pattern. Must be at least 3 characters
* long
* @param suffix the filename suffix. Can be null, in which case (system)
* default suffix is used
* @return temp file
* @throws IllegalArgumentException when pattern is null or too short
* @throws IOException when the specified (non-null) directory is not a
* directory
*/
public static File createTempFile(File directory, String pattern, String suffix)
throws IllegalArgumentException, IOException {
if ((pattern == null) || (pattern.length() < 3)) {
throw new IllegalArgumentException(
"Pattern must be at least 3 characters long, got " + ((pattern == null) ? "null" : pattern.length()));
}
if ((directory != null) && !directory.isDirectory()) {
throw new FileNotFoundException("Directory " + directory + " is not a directory");
}
return File.createTempFile(pattern, suffix, directory);
}
public static String absolutePath(File file) {
return normalizePath(file.getAbsolutePath());
}
public static String absolutePath(Path path) {
return normalizePath(path.toAbsolutePath());
}
public static String normalizePath(Path path) {
return normalizePath(path.toString());
}
public static String normalizePath(File file) {
return normalizePath(file.getPath());
}
public static String normalizePath(String path) {
return path.replace(File.separatorChar, '/');
}
public static File getFile(String file) {
return getFile(work, file);
}
public static File getFile(File base, String file) {
StringRover rover = new StringRover(file);
if (rover.startsWith("~/")) {
rover.increment(2);
if (!rover.startsWith("~/")) {
return getFile(home, rover.substring(0));
}
}
if (rover.startsWith("~")) {
return getFile(home.getParentFile(), rover.substring(1));
}
File f = new File(rover.substring(0));
if (f.isAbsolute()) {
return f;
}
if (base == null) {
base = work;
}
for (f = base.getAbsoluteFile(); !rover.isEmpty();) {
int n = rover.indexOf('/');
if (n < 0) {
n = rover.length();
}
if ((n == 0) || ((n == 1) && (rover.charAt(0) == '.'))) {
// case "" or "."
} else if ((n == 2) && (rover.charAt(0) == '.') && (rover.charAt(1) == '.')) {
// case ".."
File parent = f.getParentFile();
if (parent != null) {
f = parent;
}
} else {
String segment = rover.substring(0, n);
f = new File(f, segment);
}
rover.increment(n + 1);
}
return f.getAbsoluteFile();
}
public static File getBasedFile(File base, String file) throws IOException {
base = base.getCanonicalFile();
File child = getFile(base, file);
if (child.getCanonicalPath()
.startsWith(base.getCanonicalPath()
.concat(File.separator))) {
return child;
}
throw new IOException("The file " + child + " is outside of the base " + base);
}
public static Path getPath(String file) {
return getPath(work.toPath(), file);
}
public static Path getPath(Path base, String file) {
StringRover rover = new StringRover(file);
if (rover.startsWith("~/")) {
rover.increment(2);
if (!rover.startsWith("~/")) {
return getPath(home.toPath(), rover.substring(0));
}
}
if (rover.startsWith("~")) {
return getPath(home.toPath()
.getParent(), rover.substring(1));
}
Path f = new File(rover.substring(0)).toPath();
if (f.isAbsolute()) {
return f;
}
if (base == null) {
base = work.toPath();
}
for (f = base.normalize()
.toAbsolutePath(); !rover.isEmpty();) {
int n = rover.indexOf('/');
if (n < 0) {
n = rover.length();
}
String segment = rover.substring(0, n);
f = f.resolve(segment)
.normalize();
rover.increment(n + 1);
}
return f.toAbsolutePath();
}
public static Path getBasedPath(Path base, String file) throws IOException {
base = base.normalize()
.toAbsolutePath();
Path child = getPath(base, file);
if (child.startsWith(base)) {
return child;
}
throw new IOException("The file " + child + " is outside of the base " + base);
}
/**
* Deletes the specified file. Folders are recursively deleted.<br>
* If file(s) cannot be deleted, no feedback is provided (fail silently).
*
* @param file file to be deleted
*/
public static void delete(File file) {
delete(file.toPath());
}
/**
* Deletes the specified content of the given directory. Folders are
* recursively deleted. This method will not delete the given dir, this can
* be useful in Eclipse or other systems that detect delete-create<br>
* If file(s) cannot be deleted, no feedback is provided (fail silently).
*
* @param dir of whose contents are to be deleted
*/
public static void deleteContent(File dir) {
if (!dir.isDirectory())
return;
Stream.of(dir.listFiles())
.forEach(IO::delete);
}
/**
* Deletes the specified path. Folders are recursively deleted.<br>
* If file(s) cannot be deleted, no feedback is provided (fail silently).
*
* @param path path to be deleted
*/
public static void delete(Path path) {
try {
deleteWithException(path);
} catch (IOException e) {
// Ignore a failed delete
}
}
/**
* Deletes and creates directories
*/
public static void initialize(File dir) {
try {
deleteWithException(dir);
mkdirs(dir);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Deletes the specified file. Folders are recursively deleted.<br>
* Throws exception if any of the files could not be deleted.
*
* @param file file to be deleted
* @throws IOException if the file (or contents of a folder) could not be
* deleted
*/
public static void deleteWithException(File file) throws IOException {
deleteWithException(file.toPath());
}
/**
* Deletes the specified path. Folders are recursively deleted.<br>
* Throws exception if any of the files could not be deleted.
*
* @param path path to be deleted
* @throws IOException if the path (or contents of a folder) could not be
* deleted
*/