-
Notifications
You must be signed in to change notification settings - Fork 720
Expand file tree
/
Copy pathIOUtils.java
More file actions
3078 lines (2912 loc) · 122 KB
/
IOUtils.java
File metadata and controls
3078 lines (2912 loc) · 122 KB
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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.CharArrayWriter;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
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.Writer;
import java.net.HttpURLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.Selector;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.io.output.StringBuilderWriter;
/**
* General IO stream manipulation utilities.
* <p>
* This class provides static utility methods for input/output operations.
* <ul>
* <li>closeQuietly - these methods close a stream ignoring nulls and exceptions
* <li>toXxx/read - these methods read data from a stream
* <li>write - these methods write data to a stream
* <li>copy - these methods copy all the data from one stream to another
* <li>contentEquals - these methods compare the content of two streams
* </ul>
* <p>
* The byte-to-char methods and char-to-byte methods involve a conversion step.
* Two methods are provided in each case, one that uses the platform default
* encoding and the other which allows you to specify an encoding. You are
* encouraged to always specify an encoding because relying on the platform
* default can lead to unexpected results, for example when moving from
* development to production.
* <p>
* All the methods in this class that read a stream are buffered internally.
* This means that there is no cause to use a <code>BufferedInputStream</code>
* or <code>BufferedReader</code>. The default buffer size of 4K has been shown
* to be efficient in tests.
* <p>
* The various copy methods all delegate the actual copying to one of the following methods:
* <ul>
* <li>{@link #copyLarge(InputStream, OutputStream, byte[])}</li>
* <li>{@link #copyLarge(InputStream, OutputStream, long, long, byte[])}</li>
* <li>{@link #copyLarge(Reader, Writer, char[])}</li>
* <li>{@link #copyLarge(Reader, Writer, long, long, char[])}</li>
* </ul>
* For example, {@link #copy(InputStream, OutputStream)} calls {@link #copyLarge(InputStream, OutputStream)}
* which calls {@link #copy(InputStream, OutputStream, int)} which creates the buffer and calls
* {@link #copyLarge(InputStream, OutputStream, byte[])}.
* <p>
* Applications can re-use buffers by using the underlying methods directly.
* This may improve performance for applications that need to do a lot of copying.
* <p>
* Wherever possible, the methods in this class do <em>not</em> flush or close
* the stream. This is to avoid making non-portable assumptions about the
* streams' origin and further use. Thus the caller is still responsible for
* closing streams after use.
* <p>
* Origin of code: Excalibur.
*
* @version $Id$
*/
public class IOUtils {
// NOTE: This class is focused on InputStream, OutputStream, Reader and
// Writer. Each method should take at least one of these as a parameter,
// or return one of them.
/**
* Represents the end-of-file (or stream).
* @since 2.5 (made public)
*/
public static final int EOF = -1;
/**
* The Unix directory separator character.
*/
public static final char DIR_SEPARATOR_UNIX = '/';
/**
* The Windows directory separator character.
*/
public static final char DIR_SEPARATOR_WINDOWS = '\\';
/**
* The system directory separator character.
*/
public static final char DIR_SEPARATOR = File.separatorChar;
/**
* The Unix line separator string.
*/
public static final String LINE_SEPARATOR_UNIX = "\n";
/**
* The Windows line separator string.
*/
public static final String LINE_SEPARATOR_WINDOWS = "\r\n";
/**
* The system line separator string.
*/
public static final String LINE_SEPARATOR;
static {
// avoid security issues
final StringBuilderWriter buf = new StringBuilderWriter(4);
final PrintWriter out = new PrintWriter(buf);
out.println();
LINE_SEPARATOR = buf.toString();
out.close();
}
/**
* The default buffer size ({@value}) to use for
* {@link #copyLarge(InputStream, OutputStream)}
* and
* {@link #copyLarge(Reader, Writer)}
*/
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
/**
* The default buffer size to use for the skip() methods.
*/
private static final int SKIP_BUFFER_SIZE = 2048;
// Allocated in the relevant skip method if necessary.
/*
* These buffers are static and are shared between threads.
* This is possible because the buffers are write-only - the contents are never read.
*
* N.B. there is no need to synchronize when creating these because:
* - we don't care if the buffer is created multiple times (the data is ignored)
* - we always use the same size buffer, so if it it is recreated it will still be OK
* (if the buffer size were variable, we would need to synch. to ensure some other thread
* did not create a smaller one)
*/
private static char[] SKIP_CHAR_BUFFER;
private static byte[] SKIP_BYTE_BUFFER;
/**
* Instances should NOT be constructed in standard programming.
*/
public IOUtils() {
super();
}
//-----------------------------------------------------------------------
/**
* Closes a URLConnection.
*
* @param conn the connection to close.
* @since 2.4
*/
public static void close(final URLConnection conn) {
if (conn instanceof HttpURLConnection) {
((HttpURLConnection) conn).disconnect();
}
}
/**
* Closes an <code>Reader</code> unconditionally.
* <p>
* Equivalent to {@link Reader#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
* <p>
* Example code:
* <pre>
* char[] data = new char[1024];
* Reader in = null;
* try {
* in = new FileReader("foo.txt");
* in.read(data);
* in.close(); //close errors are handled
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(in);
* }
* </pre>
*
* @param input the Reader to close, may be null or already closed
*/
public static void closeQuietly(final Reader input) {
closeQuietly((Closeable) input);
}
/**
* Closes an <code>Writer</code> unconditionally.
* <p>
* Equivalent to {@link Writer#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
* <p>
* Example code:
* <pre>
* Writer out = null;
* try {
* out = new StringWriter();
* out.write("Hello World");
* out.close(); //close errors are handled
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(out);
* }
* </pre>
*
* @param output the Writer to close, may be null or already closed
*/
public static void closeQuietly(final Writer output) {
closeQuietly((Closeable) output);
}
/**
* Closes an <code>InputStream</code> unconditionally.
* <p>
* Equivalent to {@link InputStream#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
* <p>
* Example code:
* <pre>
* byte[] data = new byte[1024];
* InputStream in = null;
* try {
* in = new FileInputStream("foo.txt");
* in.read(data);
* in.close(); //close errors are handled
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(in);
* }
* </pre>
*
* @param input the InputStream to close, may be null or already closed
*/
public static void closeQuietly(final InputStream input) {
closeQuietly((Closeable) input);
}
/**
* Closes an <code>OutputStream</code> unconditionally.
* <p>
* Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
* <p>
* Example code:
* <pre>
* byte[] data = "Hello, World".getBytes();
*
* OutputStream out = null;
* try {
* out = new FileOutputStream("foo.txt");
* out.write(data);
* out.close(); //close errors are handled
* } catch (IOException e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(out);
* }
* </pre>
*
* @param output the OutputStream to close, may be null or already closed
*/
public static void closeQuietly(final OutputStream output) {
closeQuietly((Closeable) output);
}
/**
* Closes a <code>Closeable</code> unconditionally.
* <p>
* Equivalent to {@link Closeable#close()}, except any exceptions will be ignored. This is typically used in
* finally blocks.
* <p>
* Example code:
* </p>
* <pre>
* Closeable closeable = null;
* try {
* closeable = new FileReader("foo.txt");
* // process closeable
* closeable.close();
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(closeable);
* }
* </pre>
* <p>
* Closing all streams:
* </p>
* <pre>
* try {
* return IOUtils.copy(inputStream, outputStream);
* } finally {
* IOUtils.closeQuietly(inputStream);
* IOUtils.closeQuietly(outputStream);
* }
* </pre>
*
* @param closeable the objects to close, may be null or already closed
* @since 2.0
*/
public static void closeQuietly(final Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (final IOException ioe) {
// ignore
}
}
/**
* Closes a <code>Closeable</code> unconditionally.
* <p>
* Equivalent to {@link Closeable#close()}, except any exceptions will be ignored.
* <p>
* This is typically used in finally blocks to ensure that the closeable is closed
* even if an Exception was thrown before the normal close statement was reached.
* <br>
* <b>It should not be used to replace the close statement(s)
* which should be present for the non-exceptional case.</b>
* <br>
* It is only intended to simplify tidying up where normal processing has already failed
* and reporting close failure as well is not necessary or useful.
* <p>
* Example code:
* </p>
* <pre>
* Closeable closeable = null;
* try {
* closeable = new FileReader("foo.txt");
* // processing using the closeable; may throw an Exception
* closeable.close(); // Normal close - exceptions not ignored
* } catch (Exception e) {
* // error handling
* } finally {
* <b>IOUtils.closeQuietly(closeable); // In case normal close was skipped due to Exception</b>
* }
* </pre>
* <p>
* Closing all streams:
* <br>
* <pre>
* try {
* return IOUtils.copy(inputStream, outputStream);
* } finally {
* IOUtils.closeQuietly(inputStream, outputStream);
* }
* </pre>
*
* @param closeables the objects to close, may be null or already closed
* @see #closeQuietly(Closeable)
* @since 2.5
*/
public static void closeQuietly(final Closeable... closeables) {
if (closeables == null) {
return;
}
for (final Closeable closeable : closeables) {
closeQuietly(closeable);
}
}
/**
* Closes a <code>Socket</code> unconditionally.
* <p>
* Equivalent to {@link Socket#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
* <p>
* Example code:
* <pre>
* Socket socket = null;
* try {
* socket = new Socket("http://www.foo.com/", 80);
* // process socket
* socket.close();
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(socket);
* }
* </pre>
*
* @param sock the Socket to close, may be null or already closed
* @since 2.0
*/
public static void closeQuietly(final Socket sock) {
if (sock != null) {
try {
sock.close();
} catch (final IOException ioe) {
// ignored
}
}
}
/**
* Closes a <code>Selector</code> unconditionally.
* <p>
* Equivalent to {@link Selector#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
* <p>
* Example code:
* <pre>
* Selector selector = null;
* try {
* selector = Selector.open();
* // process socket
*
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(selector);
* }
* </pre>
*
* @param selector the Selector to close, may be null or already closed
* @since 2.2
*/
public static void closeQuietly(final Selector selector) {
if (selector != null) {
try {
selector.close();
} catch (final IOException ioe) {
// ignored
}
}
}
/**
* Closes a <code>ServerSocket</code> unconditionally.
* <p>
* Equivalent to {@link ServerSocket#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
* <p>
* Example code:
* <pre>
* ServerSocket socket = null;
* try {
* socket = new ServerSocket();
* // process socket
* socket.close();
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(socket);
* }
* </pre>
*
* @param sock the ServerSocket to close, may be null or already closed
* @since 2.2
*/
public static void closeQuietly(final ServerSocket sock) {
if (sock != null) {
try {
sock.close();
} catch (final IOException ioe) {
// ignored
}
}
}
/**
* Fetches entire contents of an <code>InputStream</code> and represent
* same data as result InputStream.
* <p>
* This method is useful where,
* <ul>
* <li>Source InputStream is slow.</li>
* <li>It has network resources associated, so we cannot keep it open for
* long time.</li>
* <li>It has network timeout associated.</li>
* </ul>
* It can be used in favor of {@link #toByteArray(InputStream)}, since it
* avoids unnecessary allocation and copy of byte[].<br>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedInputStream</code>.
*
* @param input Stream to be fully buffered.
* @return A fully buffered stream.
* @throws IOException if an I/O error occurs
* @since 2.0
*/
public static InputStream toBufferedInputStream(final InputStream input) throws IOException {
return ByteArrayOutputStream.toBufferedInputStream(input);
}
/**
* Fetches entire contents of an <code>InputStream</code> and represent
* same data as result InputStream.
* <p>
* This method is useful where,
* <ul>
* <li>Source InputStream is slow.</li>
* <li>It has network resources associated, so we cannot keep it open for
* long time.</li>
* <li>It has network timeout associated.</li>
* </ul>
* It can be used in favor of {@link #toByteArray(InputStream)}, since it
* avoids unnecessary allocation and copy of byte[].<br>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedInputStream</code>.
*
* @param input Stream to be fully buffered.
* @param size the initial buffer size
* @return A fully buffered stream.
* @throws IOException if an I/O error occurs
* @since 2.5
*/
public static InputStream toBufferedInputStream(final InputStream input, int size) throws IOException {
return ByteArrayOutputStream.toBufferedInputStream(input, size);
}
/**
* Returns the given reader if it is a {@link BufferedReader}, otherwise creates a BufferedReader from the given
* reader.
*
* @param reader the reader to wrap or return (not null)
* @return the given reader or a new {@link BufferedReader} for the given reader
* @throws NullPointerException if the input parameter is null
* @see #buffer(Reader)
* @since 2.2
*/
public static BufferedReader toBufferedReader(final Reader reader) {
return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
}
/**
* Returns the given reader if it is a {@link BufferedReader}, otherwise creates a BufferedReader from the given
* reader.
*
* @param reader the reader to wrap or return (not null)
* @param size the buffer size, if a new BufferedReader is created.
* @return the given reader or a new {@link BufferedReader} for the given reader
* @throws NullPointerException if the input parameter is null
* @see #buffer(Reader)
* @since 2.5
*/
public static BufferedReader toBufferedReader(final Reader reader, int size) {
return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader, size);
}
/**
* Returns the given reader if it is already a {@link BufferedReader}, otherwise creates a BufferedReader from
* the given reader.
*
* @param reader the reader to wrap or return (not null)
* @return the given reader or a new {@link BufferedReader} for the given reader
* @throws NullPointerException if the input parameter is null
* @since 2.5
*/
public static BufferedReader buffer(final Reader reader) {
return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
}
/**
* Returns the given reader if it is already a {@link BufferedReader}, otherwise creates a BufferedReader from the
* given reader.
*
* @param reader the reader to wrap or return (not null)
* @param size the buffer size, if a new BufferedReader is created.
* @return the given reader or a new {@link BufferedReader} for the given reader
* @throws NullPointerException if the input parameter is null
* @since 2.5
*/
public static BufferedReader buffer(final Reader reader, int size) {
return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader, size);
}
/**
* Returns the given Writer if it is already a {@link BufferedWriter}, otherwise creates a BufferedWriter from the
* given Writer.
*
* @param writer the Writer to wrap or return (not null)
* @return the given Writer or a new {@link BufferedWriter} for the given Writer
* @throws NullPointerException if the input parameter is null
* @since 2.5
*/
public static BufferedWriter buffer(final Writer writer) {
return writer instanceof BufferedWriter ? (BufferedWriter) writer : new BufferedWriter(writer);
}
/**
* Returns the given Writer if it is already a {@link BufferedWriter}, otherwise creates a BufferedWriter from the
* given Writer.
*
* @param writer the Writer to wrap or return (not null)
* @param size the buffer size, if a new BufferedWriter is created.
* @return the given Writer or a new {@link BufferedWriter} for the given Writer
* @throws NullPointerException if the input parameter is null
* @since 2.5
*/
public static BufferedWriter buffer(final Writer writer, int size) {
return writer instanceof BufferedWriter ? (BufferedWriter) writer : new BufferedWriter(writer, size);
}
/**
* Returns the given OutputStream if it is already a {@link BufferedOutputStream}, otherwise creates a
* BufferedOutputStream from the given OutputStream.
*
* @param outputStream the OutputStream to wrap or return (not null)
* @return the given OutputStream or a new {@link BufferedOutputStream} for the given OutputStream
* @throws NullPointerException if the input parameter is null
* @since 2.5
*/
public static BufferedOutputStream buffer(final OutputStream outputStream) {
// reject null early on rather than waiting for IO operation to fail
if (outputStream == null) { // not checked by BufferedOutputStream
throw new NullPointerException();
}
return outputStream instanceof BufferedOutputStream ?
(BufferedOutputStream) outputStream : new BufferedOutputStream(outputStream);
}
/**
* Returns the given OutputStream if it is already a {@link BufferedOutputStream}, otherwise creates a
* BufferedOutputStream from the given OutputStream.
*
* @param outputStream the OutputStream to wrap or return (not null)
* @param size the buffer size, if a new BufferedOutputStream is created.
* @return the given OutputStream or a new {@link BufferedOutputStream} for the given OutputStream
* @throws NullPointerException if the input parameter is null
* @since 2.5
*/
public static BufferedOutputStream buffer(final OutputStream outputStream, int size) {
// reject null early on rather than waiting for IO operation to fail
if (outputStream == null) { // not checked by BufferedOutputStream
throw new NullPointerException();
}
return outputStream instanceof BufferedOutputStream ?
(BufferedOutputStream) outputStream : new BufferedOutputStream(outputStream, size);
}
/**
* Returns the given InputStream if it is already a {@link BufferedInputStream}, otherwise creates a
* BufferedInputStream from the given InputStream.
*
* @param inputStream the InputStream to wrap or return (not null)
* @return the given InputStream or a new {@link BufferedInputStream} for the given InputStream
* @throws NullPointerException if the input parameter is null
* @since 2.5
*/
public static BufferedInputStream buffer(final InputStream inputStream) {
// reject null early on rather than waiting for IO operation to fail
if (inputStream == null) { // not checked by BufferedInputStream
throw new NullPointerException();
}
return inputStream instanceof BufferedInputStream ?
(BufferedInputStream) inputStream : new BufferedInputStream(inputStream);
}
/**
* Returns the given InputStream if it is already a {@link BufferedInputStream}, otherwise creates a
* BufferedInputStream from the given InputStream.
*
* @param inputStream the InputStream to wrap or return (not null)
* @param size the buffer size, if a new BufferedInputStream is created.
* @return the given InputStream or a new {@link BufferedInputStream} for the given InputStream
* @throws NullPointerException if the input parameter is null
* @since 2.5
*/
public static BufferedInputStream buffer(final InputStream inputStream, int size) {
// reject null early on rather than waiting for IO operation to fail
if (inputStream == null) { // not checked by BufferedInputStream
throw new NullPointerException();
}
return inputStream instanceof BufferedInputStream ?
(BufferedInputStream) inputStream : new BufferedInputStream(inputStream, size);
}
// read toByteArray
//-----------------------------------------------------------------------
/**
* Gets the contents of an <code>InputStream</code> as a <code>byte[]</code>.
* <p>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedInputStream</code>.
*
* @param input the <code>InputStream</code> to read from
* @return the requested byte array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(final InputStream input) throws IOException {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output);
return output.toByteArray();
}
/**
* Gets contents of an <code>InputStream</code> as a <code>byte[]</code>.
* Use this method instead of <code>toByteArray(InputStream)</code>
* when <code>InputStream</code> size is known.
* <b>NOTE:</b> the method checks that the length can safely be cast to an int without truncation
* before using {@link IOUtils#toByteArray(java.io.InputStream, int)} to read into the byte array.
* (Arrays can have no more than Integer.MAX_VALUE entries anyway)
*
* @param input the <code>InputStream</code> to read from
* @param size the size of <code>InputStream</code>
* @return the requested byte array
* @throws IOException if an I/O error occurs or <code>InputStream</code> size differ from parameter
* size
* @throws IllegalArgumentException if size is less than zero or size is greater than Integer.MAX_VALUE
* @see IOUtils#toByteArray(java.io.InputStream, int)
* @since 2.1
*/
public static byte[] toByteArray(final InputStream input, final long size) throws IOException {
if (size > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Size cannot be greater than Integer max value: " + size);
}
return toByteArray(input, (int) size);
}
/**
* Gets the contents of an <code>InputStream</code> as a <code>byte[]</code>.
* Use this method instead of <code>toByteArray(InputStream)</code>
* when <code>InputStream</code> size is known
*
* @param input the <code>InputStream</code> to read from
* @param size the size of <code>InputStream</code>
* @return the requested byte array
* @throws IOException if an I/O error occurs or <code>InputStream</code> size differ from parameter
* size
* @throws IllegalArgumentException if size is less than zero
* @since 2.1
*/
public static byte[] toByteArray(final InputStream input, final int size) throws IOException {
if (size < 0) {
throw new IllegalArgumentException("Size must be equal or greater than zero: " + size);
}
if (size == 0) {
return new byte[0];
}
final byte[] data = new byte[size];
int offset = 0;
int readed;
while (offset < size && (readed = input.read(data, offset, size - offset)) != EOF) {
offset += readed;
}
if (offset != size) {
throw new IOException("Unexpected readed size. current: " + offset + ", excepted: " + size);
}
return data;
}
/**
* Gets the contents of a <code>Reader</code> as a <code>byte[]</code>
* using the default character encoding of the platform.
* <p>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedReader</code>.
*
* @param input the <code>Reader</code> to read from
* @return the requested byte array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @deprecated 2.5 use {@link #toByteArray(Reader, Charset)} instead
*/
@Deprecated
public static byte[] toByteArray(final Reader input) throws IOException {
return toByteArray(input, Charset.defaultCharset());
}
/**
* Gets the contents of a <code>Reader</code> as a <code>byte[]</code>
* using the specified character encoding.
* <p>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedReader</code>.
*
* @param input the <code>Reader</code> to read from
* @param encoding the encoding to use, null means platform default
* @return the requested byte array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @since 2.3
*/
public static byte[] toByteArray(final Reader input, final Charset encoding) throws IOException {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output, encoding);
return output.toByteArray();
}
/**
* Gets the contents of a <code>Reader</code> as a <code>byte[]</code>
* using the specified character encoding.
* <p>
* Character encoding names can be found at
* <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
* <p>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedReader</code>.
*
* @param input the <code>Reader</code> to read from
* @param encoding the encoding to use, null means platform default
* @return the requested byte array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 1.1
*/
public static byte[] toByteArray(final Reader input, final String encoding) throws IOException {
return toByteArray(input, Charsets.toCharset(encoding));
}
/**
* Gets the contents of a <code>String</code> as a <code>byte[]</code>
* using the default character encoding of the platform.
* <p>
* This is the same as {@link String#getBytes()}.
*
* @param input the <code>String</code> to convert
* @return the requested byte array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs (never occurs)
* @deprecated 2.5 Use {@link String#getBytes()} instead
*/
@Deprecated
public static byte[] toByteArray(final String input) throws IOException {
// make explicit the use of the default charset
return input.getBytes(Charset.defaultCharset());
}
/**
* Gets the contents of a <code>URI</code> as a <code>byte[]</code>.
*
* @param uri the <code>URI</code> to read
* @return the requested byte array
* @throws NullPointerException if the uri is null
* @throws IOException if an I/O exception occurs
* @since 2.4
*/
public static byte[] toByteArray(final URI uri) throws IOException {
return IOUtils.toByteArray(uri.toURL());
}
/**
* Gets the contents of a <code>URL</code> as a <code>byte[]</code>.
*
* @param url the <code>URL</code> to read
* @return the requested byte array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O exception occurs
* @since 2.4
*/
public static byte[] toByteArray(final URL url) throws IOException {
final URLConnection conn = url.openConnection();
try {
return IOUtils.toByteArray(conn);
} finally {
close(conn);
}
}
/**
* Gets the contents of a <code>URLConnection</code> as a <code>byte[]</code>.
*
* @param urlConn the <code>URLConnection</code> to read
* @return the requested byte array
* @throws NullPointerException if the urlConn is null
* @throws IOException if an I/O exception occurs
* @since 2.4
*/
public static byte[] toByteArray(final URLConnection urlConn) throws IOException {
final InputStream inputStream = urlConn.getInputStream();
try {
return IOUtils.toByteArray(inputStream);
} finally {
inputStream.close();
}
}
// read char[]
//-----------------------------------------------------------------------
/**
* Gets the contents of an <code>InputStream</code> as a character array
* using the default character encoding of the platform.
* <p>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedInputStream</code>.
*
* @param is the <code>InputStream</code> to read from
* @return the requested character array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @since 1.1
* @deprecated 2.5 use {@link #toCharArray(InputStream, Charset)} instead
*/
@Deprecated
public static char[] toCharArray(final InputStream is) throws IOException {
return toCharArray(is, Charset.defaultCharset());
}
/**
* Gets the contents of an <code>InputStream</code> as a character array
* using the specified character encoding.
* <p>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedInputStream</code>.
*
* @param is the <code>InputStream</code> to read from
* @param encoding the encoding to use, null means platform default
* @return the requested character array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @since 2.3
*/
public static char[] toCharArray(final InputStream is, final Charset encoding)
throws IOException {
final CharArrayWriter output = new CharArrayWriter();
copy(is, output, encoding);
return output.toCharArray();
}
/**
* Gets the contents of an <code>InputStream</code> as a character array
* using the specified character encoding.
* <p>
* Character encoding names can be found at
* <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
* <p>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedInputStream</code>.
*
* @param is the <code>InputStream</code> to read from
* @param encoding the encoding to use, null means platform default
* @return the requested character array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 1.1
*/
public static char[] toCharArray(final InputStream is, final String encoding) throws IOException {
return toCharArray(is, Charsets.toCharset(encoding));
}
/**
* Gets the contents of a <code>Reader</code> as a character array.
* <p>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedReader</code>.
*
* @param input the <code>Reader</code> to read from
* @return the requested character array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @since 1.1
*/
public static char[] toCharArray(final Reader input) throws IOException {
final CharArrayWriter sw = new CharArrayWriter();
copy(input, sw);
return sw.toCharArray();