-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
IOUtils.java
2029 lines (1863 loc) · 67.2 KB
/
IOUtils.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 edu.stanford.nlp.io;
import edu.stanford.nlp.util.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Helper Class for various I/O related things.
*
* @author Kayur Patel, Teg Grenager
*/
public class IOUtils {
private static final int SLURP_BUFFER_SIZE = 16000;
private static final int GZIP_FILE_BUFFER_SIZE = 65536;
public static final String eolChar = System.getProperty("line.separator");
public static final String defaultEncoding = "utf-8";
// A class of static methods
private IOUtils() { }
/**
* Write object to a file with the specified name. The file is silently gzipped if the filename ends with .gz.
*
* @param o Object to be written to file
* @param filename Name of the temp file
* @throws IOException If can't write file.
* @return File containing the object
*/
public static File writeObjectToFile(Object o, String filename)
throws IOException {
return writeObjectToFile(o, new File(filename));
}
/**
* Write an object to a specified File. The file is silently gzipped if the filename ends with .gz.
*
* @param o Object to be written to file
* @param file The temp File
* @throws IOException If File cannot be written
* @return File containing the object
*/
public static File writeObjectToFile(Object o, File file) throws IOException {
return writeObjectToFile(o, file, false);
}
/**
* Write an object to a specified File. The file is silently gzipped if the filename ends with .gz.
*
* @param o Object to be written to file
* @param file The temp File
* @param append If true, append to this file instead of overwriting it
* @throws IOException If File cannot be written
* @return File containing the object
*/
public static File writeObjectToFile(Object o, File file, boolean append) throws IOException {
// file.createNewFile(); // cdm may 2005: does nothing needed
OutputStream os = new FileOutputStream(file, append);
if (file.getName().endsWith(".gz")) {
os = new GZIPOutputStream(os);
}
os = new BufferedOutputStream(os);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(o);
oos.close();
return file;
}
/**
* Write object to a file with the specified name.
*
* @param o Object to be written to file
* @param filename Name of the temp file
* @return File containing the object, or null if an exception was caught
*/
public static File writeObjectToFileNoExceptions(Object o, String filename) {
File file = null;
ObjectOutputStream oos = null;
try {
file = new File(filename);
// file.createNewFile(); // cdm may 2005: does nothing needed
oos = new ObjectOutputStream(new BufferedOutputStream(
new GZIPOutputStream(new FileOutputStream(file))));
oos.writeObject(o);
oos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeIgnoringExceptions(oos);
}
return file;
}
/**
* Write object to temp file which is destroyed when the program exits.
*
* @param o Object to be written to file
* @param filename Name of the temp file
* @throws IOException If file cannot be written
* @return File containing the object
*/
public static File writeObjectToTempFile(Object o, String filename)
throws IOException {
File file = File.createTempFile(filename, ".tmp");
file.deleteOnExit();
writeObjectToFile(o, file);
return file;
}
/**
* Write object to a temp file and ignore exceptions.
*
* @param o Object to be written to file
* @param filename Name of the temp file
* @return File containing the object
*/
public static File writeObjectToTempFileNoExceptions(Object o, String filename) {
try {
return writeObjectToTempFile(o, filename);
} catch (Exception e) {
System.err.println("Error writing object to file " + filename);
e.printStackTrace();
return null;
}
}
private static OutputStream getBufferedOutputStream(String path) throws IOException {
OutputStream os = new BufferedOutputStream(new FileOutputStream(path));
if (path.endsWith(".gz")) {
os = new GZIPOutputStream(os);
}
return os;
}
//++ todo [cdm, Aug 2012]: Do we need the below methods? They're kind of weird in unnecessarily bypassing using a Writer.
/**
* Writes a string to a file.
*
* @param contents The string to write
* @param path The file path
* @param encoding The encoding to encode in
* @throws IOException In case of failure
*/
public static void writeStringToFile(String contents, String path, String encoding) throws IOException {
OutputStream writer = getBufferedOutputStream(path);
writer.write(contents.getBytes(encoding));
writer.close();
}
/**
* Writes a string to a file, as UTF-8.
*
* @param contents The string to write
* @param path The file path
* @throws IOException In case of failure
*/
/**
* Writes a string to a file, squashing exceptions
*
* @param contents The string to write
* @param path The file path
* @param encoding The encoding to encode in
* */
public static void writeStringToFileNoExceptions(String contents, String path, String encoding) {
OutputStream writer = null;
try{
if (path.endsWith(".gz")) {
writer = new GZIPOutputStream(new FileOutputStream(path));
} else {
writer = new BufferedOutputStream(new FileOutputStream(path));
}
writer.write(contents.getBytes(encoding));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(writer != null){ closeIgnoringExceptions(writer); }
}
}
/**
* Writes a string to a temporary file
*
* @param contents The string to write
* @param path The file path
* @param encoding The encoding to encode in
* @throws IOException In case of failure
* @return The File written to
*/
public static File writeStringToTempFile(String contents, String path, String encoding) throws IOException {
OutputStream writer;
File tmp = File.createTempFile(path,".tmp");
if (path.endsWith(".gz")) {
writer = new GZIPOutputStream(new FileOutputStream(tmp));
} else {
writer = new BufferedOutputStream(new FileOutputStream(tmp));
}
writer.write(contents.getBytes(encoding));
return tmp;
}
/**
* Writes a string to a temporary file, as UTF-8
*
* @param contents The string to write
* @param path The file path
* @throws IOException In case of failure
*/
public static void writeStringToTempFile(String contents, String path) throws IOException {
writeStringToTempFile(contents, path, "UTF-8");
}
/**
* Writes a string to a temporary file, squashing exceptions
*
* @param contents The string to write
* @param path The file path
* @param encoding The encoding to encode in
* @return The File that was written to
*/
public static File writeStringToTempFileNoExceptions(String contents, String path, String encoding) {
OutputStream writer = null;
File tmp = null;
try {
tmp = File.createTempFile(path,".tmp");
if (path.endsWith(".gz")) {
writer = new GZIPOutputStream(new FileOutputStream(tmp));
} else {
writer = new BufferedOutputStream(new FileOutputStream(tmp));
}
writer.write(contents.getBytes(encoding));
} catch (Exception e) {
e.printStackTrace();
} finally {
closeIgnoringExceptions(writer);
}
return tmp;
}
/**
* Writes a string to a temporary file with UTF-8 encoding, squashing exceptions
*
* @param contents The string to write
* @param path The file path
*/
public static void writeStringToTempFileNoExceptions(String contents, String path) {
writeStringToTempFileNoExceptions(contents, path, "UTF-8");
}
//-- todo [cdm, Aug 2012]: Do we need the below methods? They're kind of weird in unnecessarily bypassing using a Writer.
// todo [cdm, Sep 2013]: Can we remove this next method and its friends? (Weird in silently gzipping, overlaps other functionality.)
/**
* Read an object from a stored file. It is silently ungzipped, regardless of name.
*
* @param file The file pointing to the object to be retrieved
* @throws IOException If file cannot be read
* @throws ClassNotFoundException If reading serialized object fails
* @return The object read from the file.
*/
public static <T> T readObjectFromFile(File file) throws IOException,
ClassNotFoundException {
try {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(
new GZIPInputStream(new FileInputStream(file))));
Object o = ois.readObject();
ois.close();
return ErasureUtils.uncheckedCast(o);
} catch (java.util.zip.ZipException e) {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(
new FileInputStream(file)));
Object o = ois.readObject();
ois.close();
return ErasureUtils.uncheckedCast(o);
}
}
public static DataInputStream getDataInputStream(String filenameUrlOrClassPath) throws IOException {
return new DataInputStream(getInputStreamFromURLOrClasspathOrFileSystem(filenameUrlOrClassPath));
}
public static DataOutputStream getDataOutputStream(String filename) throws IOException {
return new DataOutputStream(getBufferedOutputStream((filename)));
}
/**
* Read an object from a stored file. The file can be anything obtained
* via a URL, the filesystem, or the classpath (eg in a jar file).
*
* @param filename The file pointing to the object to be retrieved
* @throws IOException If file cannot be read
* @throws ClassNotFoundException If reading serialized object fails
* @return The object read from the file.
*/
public static <T> T readObjectFromURLOrClasspathOrFileSystem(String filename) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(getInputStreamFromURLOrClasspathOrFileSystem(filename));
Object o = ois.readObject();
ois.close();
return ErasureUtils.uncheckedCast(o);
}
public static <T> T readObjectFromObjectStream(ObjectInputStream ois) throws IOException,
ClassNotFoundException {
Object o = ois.readObject();
return ErasureUtils.uncheckedCast(o);
}
/**
* Read an object from a stored file.
*
* @param filename The filename of the object to be retrieved
* @throws IOException If file cannot be read
* @throws ClassNotFoundException If reading serialized object fails
* @return The object read from the file.
*/
public static <T> T readObjectFromFile(String filename) throws IOException,
ClassNotFoundException {
return ErasureUtils.uncheckedCast(readObjectFromFile(new File(filename)));
}
/**
* Read an object from a stored file without throwing exceptions.
*
* @param file The file pointing to the object to be retrieved
* @return The object read from the file, or null if an exception occurred.
*/
public static <T> T readObjectFromFileNoExceptions(File file) {
Object o = null;
try {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(
new GZIPInputStream(new FileInputStream(file))));
o = ois.readObject();
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ErasureUtils.uncheckedCast(o);
}
public static int lineCount(String textFileOrUrl) throws IOException {
BufferedReader r = readerFromString(textFileOrUrl);
int numLines = 0;
while (r.readLine() != null) {
numLines++;
}
return numLines;
}
public static ObjectOutputStream writeStreamFromString(String serializePath)
throws IOException {
ObjectOutputStream oos;
if (serializePath.endsWith(".gz")) {
oos = new ObjectOutputStream(new BufferedOutputStream(
new GZIPOutputStream(new FileOutputStream(serializePath))));
} else {
oos = new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(serializePath)));
}
return oos;
}
public static ObjectInputStream readStreamFromString(String filenameOrUrl)
throws IOException {
InputStream is = getInputStreamFromURLOrClasspathOrFileSystem(filenameOrUrl);
return new ObjectInputStream(is);
}
/**
* Locates this file either in the CLASSPATH or in the file system. The CLASSPATH takes priority.
*
* @param name The file or resource name
* @throws FileNotFoundException If the file does not exist
* @return The InputStream of name, or null if not found
*/
private static InputStream findStreamInClasspathOrFileSystem(String name) throws FileNotFoundException {
// ms 10-04-2010:
// - even though this may look like a regular file, it may be a path inside a jar in the CLASSPATH
// - check for this first. This takes precedence over the file system.
InputStream is = IOUtils.class.getClassLoader().getResourceAsStream(name);
// windows File.separator is \, but getting resources only works with /
if (is == null) {
is = IOUtils.class.getClassLoader().getResourceAsStream(name.replaceAll("\\\\", "/"));
}
// if not found in the CLASSPATH, load from the file system
if (is == null) is = new FileInputStream(name);
return is;
}
/**
* Check if this path exists either in the classpath or on the filesystem.
*
* @param name The file or resource name.
* @return true if a call to {@link IOUtils#getBufferedReaderFromClasspathOrFileSystem(String)} would return a valid stream.
*/
public static boolean existsInClasspathOrFileSystem(String name) {
InputStream is = IOUtils.class.getClassLoader().getResourceAsStream(name);
if (is == null) {
is = IOUtils.class.getClassLoader().getResourceAsStream(name.replaceAll("\\\\", "/"));
}
return is != null || new File(name).exists();
}
/**
* Locates this file either using the given URL, or in the CLASSPATH, or in the file system
* The CLASSPATH takes priority over the file system!
* This stream is buffered and gunzipped (if necessary).
*
* @param textFileOrUrl
* @return An InputStream for loading a resource
* @throws IOException
*/
public static InputStream getInputStreamFromURLOrClasspathOrFileSystem(String textFileOrUrl)
throws IOException
{
InputStream in;
if (textFileOrUrl.matches("https?://.*")) {
URL u = new URL(textFileOrUrl);
URLConnection uc = u.openConnection();
in = uc.getInputStream();
} else {
try {
in = findStreamInClasspathOrFileSystem(textFileOrUrl);
} catch (FileNotFoundException e) {
try {
// Maybe this happens to be some other format of URL?
URL u = new URL(textFileOrUrl);
URLConnection uc = u.openConnection();
in = uc.getInputStream();
} catch (IOException e2) {
// Don't make the original exception a cause, since it is almost certainly bogus
throw new IOException("Unable to resolve \"" +
textFileOrUrl + "\" as either " +
"class path, filename or URL"); // , e2);
}
}
}
if (textFileOrUrl.endsWith(".gz")) {
// gunzip it if necessary
in = new GZIPInputStream(in, GZIP_FILE_BUFFER_SIZE);
}
// buffer this stream. even gzip streams benefit from buffering,
// such as for the shift reduce parser
in = new BufferedInputStream(in);
return in;
}
/**
* Quietly opens a File. If the file ends with a ".gz" extension,
* automatically opens a GZIPInputStream to wrap the constructed
* FileInputStream.
*/
public static InputStream inputStreamFromFile(File file) throws RuntimeIOException {
try {
InputStream is = new BufferedInputStream(new FileInputStream(file));
if (file.getName().endsWith(".gz")) {
is = new GZIPInputStream(is);
}
return is;
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
/**
* Open a BufferedReader to a File. If the file's getName() ends in .gz,
* it is interpreted as a gzipped file (and uncompressed). The file is then
* interpreted as a utf-8 text file.
*
* @param file What to read from
* @return The BufferedReader
* @throws RuntimeIOException If there is an I/O problem
*/
public static BufferedReader readerFromFile(File file) {
InputStream is = null;
try {
is = inputStreamFromFile(file);
return new BufferedReader(new InputStreamReader(is, "UTF-8"));
} catch (IOException ioe) {
IOUtils.closeIgnoringExceptions(is);
throw new RuntimeIOException(ioe);
}
}
/**
* Open a BufferedReader to a File. If the file's getName() ends in .gz,
* it is interpreted as a gzipped file (and uncompressed). The file is then
* turned into a BufferedReader with the given encoding.
* If the encoding passed in is null, then the system default encoding is used.
*
* @param file What to read from
* @param encoding What charset to use. A null String is interpreted as platform default encoding
* @return The BufferedReader
* @throws RuntimeIOException If there is an I/O problem
*/
public static BufferedReader readerFromFile(File file, String encoding) {
InputStream is = null;
try {
is = inputStreamFromFile(file);
if (encoding == null) {
return new BufferedReader(new InputStreamReader(is));
} else {
return new BufferedReader(new InputStreamReader(is, encoding));
}
} catch (IOException ioe) {
IOUtils.closeIgnoringExceptions(is);
throw new RuntimeIOException(ioe);
}
}
/**
* Open a BufferedReader on stdin. Use the user's default encoding.
*
* @return The BufferedReader
* @throws IOException If there is an I/O problem
*/
public static BufferedReader readerFromStdin() throws IOException {
return new BufferedReader(new InputStreamReader(System.in));
}
/**
* Open a BufferedReader on stdin. Use the specified character encoding.
*
* @param encoding CharSet encoding. Maybe be null, in which case the
* platform default encoding is used
* @return The BufferedReader
* @throws IOException If there is an I/O problem
*/
public static BufferedReader readerFromStdin(String encoding) throws IOException {
if (encoding == null) {
return new BufferedReader(new InputStreamReader(System.in));
}
return new BufferedReader(new InputStreamReader(System.in, encoding));
}
/**
* Open a BufferedReader to a file, class path entry or URL specified by a String name.
* If the String starts with https?://, then it is first tried as a URL. It
* is next tried as a resource on the CLASSPATH, and then it is tried
* as a local file. Finally, it is then tried again in case it is some network-available
* file accessible by URL. If the String ends in .gz, it
* is interpreted as a gzipped file (and uncompressed). The file is then
* interpreted as a utf-8 text file.
*
* @param textFileOrUrl What to read from
* @return The BufferedReader
* @throws IOException If there is an I/O problem
*/
public static BufferedReader readerFromString(String textFileOrUrl)
throws IOException {
return new BufferedReader(new InputStreamReader(
getInputStreamFromURLOrClasspathOrFileSystem(textFileOrUrl), "UTF-8"));
}
/**
* Open a BufferedReader to a file or URL specified by a String name. If the
* String starts with https?://, then it is first tried as a URL, otherwise it
* is next tried as a resource on the CLASSPATH, and then finally it is tried
* as a local file or other network-available file . If the String ends in .gz, it
* is interpreted as a gzipped file (and uncompressed), else it is interpreted as
* a regular text file in the given encoding.
* If the encoding passed in is null, then the system default encoding is used.
*
* @param textFileOrUrl What to read from
* @param encoding CharSet encoding. Maybe be null, in which case the
* platform default encoding is used
* @return The BufferedReader
* @throws IOException If there is an I/O problem
*/
public static BufferedReader readerFromString(String textFileOrUrl,
String encoding) throws IOException {
InputStream is = getInputStreamFromURLOrClasspathOrFileSystem(textFileOrUrl);
if (encoding == null) {
return new BufferedReader(new InputStreamReader(is));
}
return new BufferedReader(new InputStreamReader(is, encoding));
}
/**
* Returns an Iterable of the lines in the file.
*
* The file reader will be closed when the iterator is exhausted. IO errors
* will throw an (unchecked) RuntimeIOException
*
* @param path The file whose lines are to be read.
* @return An Iterable containing the lines from the file.
*/
public static Iterable<String> readLines(String path) {
return readLines(path, null);
}
/**
* Returns an Iterable of the lines in the file.
*
* The file reader will be closed when the iterator is exhausted. IO errors
* will throw an (unchecked) RuntimeIOException
*
* @param path The file whose lines are to be read.
* @param encoding The encoding to use when reading lines.
* @return An Iterable containing the lines from the file.
*/
public static Iterable<String> readLines(String path, String encoding) {
return new GetLinesIterable(path, null, encoding);
}
/**
* Returns an Iterable of the lines in the file.
*
* The file reader will be closed when the iterator is exhausted.
*
* @param file The file whose lines are to be read.
* @return An Iterable containing the lines from the file.
*/
public static Iterable<String> readLines(final File file) {
return readLines(file, null, null);
}
/**
* Returns an Iterable of the lines in the file.
*
* The file reader will be closed when the iterator is exhausted.
*
* @param file The file whose lines are to be read.
* @param fileInputStreamWrapper
* The class to wrap the InputStream with, e.g. GZIPInputStream. Note
* that the class must have a constructor that accepts an
* InputStream.
* @return An Iterable containing the lines from the file.
*/
public static Iterable<String> readLines(final File file,
final Class<? extends InputStream> fileInputStreamWrapper) {
return readLines(file, fileInputStreamWrapper, null);
}
/**
* Returns an Iterable of the lines in the file, wrapping the generated
* FileInputStream with an instance of the supplied class. IO errors will
* throw an (unchecked) RuntimeIOException
*
* @param file The file whose lines are to be read.
* @param fileInputStreamWrapper
* The class to wrap the InputStream with, e.g. GZIPInputStream. Note
* that the class must have a constructor that accepts an
* InputStream.
* @param encoding The encoding to use when reading lines.
* @return An Iterable containing the lines from the file.
*/
public static Iterable<String> readLines(final File file,
final Class<? extends InputStream> fileInputStreamWrapper,
final String encoding) {
return new GetLinesIterable(file, fileInputStreamWrapper, encoding);
}
static class GetLinesIterable implements Iterable<String> {
final File file;
final String path;
final Class<? extends InputStream> fileInputStreamWrapper;
final String encoding;
// TODO: better programming style would be to make this two
// separate classes, but we don't expect to make more versions of
// this class anyway
GetLinesIterable(final File file,
final Class<? extends InputStream> fileInputStreamWrapper,
final String encoding) {
this.file = file;
this.path = null;
this.fileInputStreamWrapper = fileInputStreamWrapper;
this.encoding = encoding;
}
GetLinesIterable(final String path,
final Class<? extends InputStream> fileInputStreamWrapper,
final String encoding) {
this.file = null;
this.path = path;
this.fileInputStreamWrapper = fileInputStreamWrapper;
this.encoding = encoding;
}
private InputStream getStream() throws IOException {
if (file != null) {
return new FileInputStream(file);
} else if (path != null) {
return getInputStreamFromURLOrClasspathOrFileSystem(path);
} else {
throw new AssertionError("No known path to read");
}
}
public Iterator<String> iterator() {
return new Iterator<String>() {
protected BufferedReader reader = this.getReader();
protected String line = this.getLine();
public boolean hasNext() {
return this.line != null;
}
public String next() {
String nextLine = this.line;
if (nextLine == null) {
throw new NoSuchElementException();
}
line = getLine();
return nextLine;
}
protected String getLine() {
try {
String result = this.reader.readLine();
if (result == null) {
this.reader.close();
}
return result;
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
protected BufferedReader getReader() {
try {
InputStream stream = getStream();
if (fileInputStreamWrapper != null) {
stream = fileInputStreamWrapper.getConstructor(InputStream.class).newInstance(stream);
}
if (encoding == null) {
return new BufferedReader(new InputStreamReader(stream));
} else {
return new BufferedReader(new InputStreamReader(stream, encoding));
}
} catch (Exception e) {
throw new RuntimeIOException(e);
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
/**
* Given a reader, returns the lines from the reader as an Iterable.
*
* @param r input reader
* @param includeEol whether to keep eol-characters in the returned strings
* @return iterable of lines (as strings)
*/
public static Iterable<String> getLineIterable( Reader r, boolean includeEol) {
if (includeEol) {
return new EolPreservingLineReaderIterable(r);
} else {
return new LineReaderIterable( (r instanceof BufferedReader)? (BufferedReader) r:new BufferedReader(r) );
}
}
public static Iterable<String> getLineIterable( Reader r, int bufferSize, boolean includeEol) {
if (includeEol) {
return new EolPreservingLineReaderIterable(r, bufferSize);
} else {
return new LineReaderIterable( (r instanceof BufferedReader)? (BufferedReader) r:new BufferedReader(r, bufferSize) );
}
}
/**
* Line iterator that uses BufferedReader.readLine()
* EOL-characters are automatically discarded and not included in the strings returns
*/
private static final class LineReaderIterable implements Iterable<String>
{
private final BufferedReader reader;
private LineReaderIterable( BufferedReader reader )
{
this.reader = reader;
}
@Override
public Iterator<String> iterator()
{
return new Iterator<String>() {
private String next = getNext();
private String getNext() {
try {
return reader.readLine();
} catch (IOException ex) {
throw new RuntimeIOException(ex);
}
}
@Override
public boolean hasNext()
{
return this.next != null;
}
@Override
public String next()
{
String nextLine = this.next;
if (nextLine == null) {
throw new NoSuchElementException();
}
next = getNext();
return nextLine;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
}
/**
* Line iterator that preserves the eol-character exactly as read from reader.
* Line endings are: \r\n,\n,\r
* Lines returns by this iterator will include the eol-characters
**/
private static final class EolPreservingLineReaderIterable implements Iterable<String>
{
private final Reader reader;
private final int bufferSize;
private EolPreservingLineReaderIterable( Reader reader )
{
this(reader, SLURP_BUFFER_SIZE);
}
private EolPreservingLineReaderIterable( Reader reader, int bufferSize )
{
this.reader = reader;
this.bufferSize = bufferSize;
}
@Override
public Iterator<String> iterator()
{
return new Iterator<String>() {
private String next;
private boolean done = false;
private StringBuilder sb = new StringBuilder(80);
private char[] charBuffer = new char[bufferSize];
private int charBufferPos = -1;
private int charsInBuffer = 0;
boolean lastWasLF = false;
private String getNext() {
try {
while (true) {
if (charBufferPos < 0) {
charsInBuffer = reader.read(charBuffer);
if (charsInBuffer < 0) {
// No more!!!
if (sb.length() > 0) {
String line = sb.toString();
// resets the buffer
sb.setLength(0);
return line;
} else {
return null;
}
}
charBufferPos = 0;
}
boolean eolReached = copyUntilEol();
if (eolReached) {
// eol reached
String line = sb.toString();
// resets the buffer
sb.setLength(0);
return line;
}
}
} catch (IOException ex) {
throw new RuntimeIOException(ex);
}
}
private boolean copyUntilEol() {
for (int i = charBufferPos; i < charsInBuffer; i++) {
if (charBuffer[i] == '\n') {
// line end
// copy into our string builder
sb.append(charBuffer, charBufferPos, i - charBufferPos + 1);
// advance character buffer pos
charBufferPos = i+1;
lastWasLF = false;
return true; // end of line reached
} else if (lastWasLF) {
// not a '\n' here - still need to terminate line (but don't include current character)
if (i > charBufferPos) {
sb.append(charBuffer, charBufferPos, i - charBufferPos);
// advance character buffer pos
charBufferPos = i;
lastWasLF = false;
return true; // end of line reached
}
}
lastWasLF = (charBuffer[i] == '\r');
}
sb.append(charBuffer, charBufferPos, charsInBuffer - charBufferPos);
// reset character buffer pos
charBufferPos = -1;
return false;
}
@Override
public boolean hasNext()
{
if (done) return false;
if (next == null) {
next = getNext();
}
if (next == null) {
done = true;
}
return !done;
}
@Override
public String next()
{
if (!hasNext()) { throw new NoSuchElementException(); }
String res = next;
next = null;
return res;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
}
/**
* Provides an implementation of closing a file for use in a finally block so
* you can correctly close a file without even more exception handling stuff.
* From a suggestion in a talk by Josh Bloch.
*
* @param c The IO resource to close (e.g., a Stream/Reader)
*/
public static void closeIgnoringExceptions(Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException ioe) {
// ignore
}
}
}
/**
* Iterate over all the files in the directory, recursively.
*
* @param dir
* The root directory.
* @return All files within the directory.
*/
public static Iterable<File> iterFilesRecursive(final File dir) {
return iterFilesRecursive(dir, (Pattern) null);
}
/**
* Iterate over all the files in the directory, recursively.
*
* @param dir
* The root directory.
* @param ext