• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 package org.apache.commons.io;
18 
19 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
20 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
21 import static org.junit.jupiter.api.Assertions.assertEquals;
22 import static org.junit.jupiter.api.Assertions.assertFalse;
23 import static org.junit.jupiter.api.Assertions.assertNotNull;
24 import static org.junit.jupiter.api.Assertions.assertNotSame;
25 import static org.junit.jupiter.api.Assertions.assertNull;
26 import static org.junit.jupiter.api.Assertions.assertSame;
27 import static org.junit.jupiter.api.Assertions.assertThrows;
28 import static org.junit.jupiter.api.Assertions.assertTrue;
29 
30 import java.io.BufferedInputStream;
31 import java.io.BufferedOutputStream;
32 import java.io.BufferedReader;
33 import java.io.BufferedWriter;
34 import java.io.ByteArrayInputStream;
35 import java.io.ByteArrayOutputStream;
36 import java.io.CharArrayReader;
37 import java.io.CharArrayWriter;
38 import java.io.Closeable;
39 import java.io.EOFException;
40 import java.io.File;
41 import java.io.FileInputStream;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.InputStreamReader;
45 import java.io.OutputStream;
46 import java.io.Reader;
47 import java.io.StringReader;
48 import java.io.Writer;
49 import java.net.ServerSocket;
50 import java.net.Socket;
51 import java.net.URI;
52 import java.net.URL;
53 import java.net.URLConnection;
54 import java.nio.ByteBuffer;
55 import java.nio.channels.FileChannel;
56 import java.nio.channels.Selector;
57 import java.nio.charset.Charset;
58 import java.nio.charset.StandardCharsets;
59 import java.nio.file.Files;
60 import java.nio.file.Path;
61 import java.util.Arrays;
62 import java.util.List;
63 import java.util.function.Supplier;
64 import java.util.stream.Stream;
65 
66 import org.apache.commons.io.function.IOConsumer;
67 import org.apache.commons.io.input.BrokenInputStream;
68 import org.apache.commons.io.input.CharSequenceInputStream;
69 import org.apache.commons.io.input.CircularInputStream;
70 import org.apache.commons.io.input.NullInputStream;
71 import org.apache.commons.io.input.NullReader;
72 import org.apache.commons.io.output.AppendableWriter;
73 import org.apache.commons.io.output.BrokenOutputStream;
74 import org.apache.commons.io.output.CountingOutputStream;
75 import org.apache.commons.io.output.NullOutputStream;
76 import org.apache.commons.io.output.NullWriter;
77 import org.apache.commons.io.output.StringBuilderWriter;
78 import org.apache.commons.io.test.TestUtils;
79 import org.apache.commons.io.test.ThrowOnCloseReader;
80 import org.apache.commons.lang3.StringUtils;
81 import org.junit.jupiter.api.AfterAll;
82 import org.junit.jupiter.api.BeforeAll;
83 import org.junit.jupiter.api.BeforeEach;
84 import org.junit.jupiter.api.Disabled;
85 import org.junit.jupiter.api.Test;
86 import org.junit.jupiter.api.io.TempDir;
87 
88 /**
89  * This is used to test {@link IOUtils} for correctness. The following checks are performed:
90  * <ul>
91  * <li>The return must not be null, must be the same type and equals() to the method's second arg</li>
92  * <li>All bytes must have been read from the source (available() == 0)</li>
93  * <li>The source and destination content must be identical (byte-wise comparison check)</li>
94  * <li>The output stream must not have been closed (a byte/char is written to test this, and subsequent size
95  * checked)</li>
96  * </ul>
97  * Due to interdependencies in IOUtils and IOUtilsTest, one bug may cause multiple tests to fail.
98  */
99 @SuppressWarnings("deprecation") // deliberately testing deprecated code
100 public class IOUtilsTest {
101 
102     private static final String UTF_8 = StandardCharsets.UTF_8.name();
103 
104     private static final int FILE_SIZE = 1024 * 4 + 1;
105 
106     /** Determine if this is windows. */
107     private static final boolean WINDOWS = File.separatorChar == '\\';
108 
109     /*
110      * Note: this is not particularly beautiful code. A better way to check for flush and close status would be to
111      * implement "trojan horse" wrapper implementations of the various stream classes, which set a flag when relevant
112      * methods are called. (JT)
113      */
114 
115     @BeforeAll
116     @AfterAll
beforeAll()117     public static void beforeAll() {
118         // Not required, just to exercise the method and make sure there are no adverse side-effect when recycling thread locals.
119         IO.clear();
120     }
121 
122     @TempDir
123     public File temporaryFolder;
124 
125     private char[] carr;
126 
127     private byte[] iarr;
128 
129     private File testFile;
130 
131     /**
132      * Path constructed from {@code testFile}.
133      */
134     private Path testFilePath;
135 
136     /** Assert that the contents of two byte arrays are the same. */
assertEqualContent(final byte[] b0, final byte[] b1)137     private void assertEqualContent(final byte[] b0, final byte[] b1) {
138         assertArrayEquals(b0, b1, "Content not equal according to java.util.Arrays#equals()");
139     }
140 
141     @BeforeEach
setUp()142     public void setUp() {
143         try {
144             testFile = new File(temporaryFolder, "file2-test.txt");
145             testFilePath = testFile.toPath();
146 
147             if (!testFile.getParentFile().exists()) {
148                 throw new IOException("Cannot create file " + testFile + " as the parent directory does not exist");
149             }
150             final BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(testFilePath));
151             try {
152                 TestUtils.generateTestData(output, FILE_SIZE);
153             } finally {
154                 IOUtils.closeQuietly(output);
155             }
156         } catch (final IOException ioe) {
157             throw new RuntimeException(
158                 "Can't run this test because the environment could not be built: " + ioe.getMessage());
159         }
160         // Create and init a byte array as input data
161         iarr = new byte[200];
162         Arrays.fill(iarr, (byte) -1);
163         for (int i = 0; i < 80; i++) {
164             iarr[i] = (byte) i;
165         }
166         carr = new char[200];
167         Arrays.fill(carr, (char) -1);
168         for (int i = 0; i < 80; i++) {
169             carr[i] = (char) i;
170         }
171     }
172 
173     @Test
testAsBufferedInputStream()174     public void testAsBufferedInputStream() {
175         final InputStream is = new InputStream() {
176             @Override
177             public int read() throws IOException {
178                 return 0;
179             }
180         };
181         final BufferedInputStream bis = IOUtils.buffer(is);
182         assertNotSame(is, bis);
183         assertSame(bis, IOUtils.buffer(bis));
184     }
185 
186     @Test
testAsBufferedInputStreamWithBufferSize()187     public void testAsBufferedInputStreamWithBufferSize() {
188         final InputStream is = new InputStream() {
189             @Override
190             public int read() throws IOException {
191                 return 0;
192             }
193         };
194         final BufferedInputStream bis = IOUtils.buffer(is, 2048);
195         assertNotSame(is, bis);
196         assertSame(bis, IOUtils.buffer(bis));
197         assertSame(bis, IOUtils.buffer(bis, 1024));
198     }
199 
200     @Test
testAsBufferedNull()201     public void testAsBufferedNull() {
202         final String npeExpectedMessage = "Expected NullPointerException";
203         assertThrows(NullPointerException.class, () -> IOUtils.buffer((InputStream) null), npeExpectedMessage);
204         assertThrows(NullPointerException.class, () -> IOUtils.buffer((OutputStream) null), npeExpectedMessage);
205         assertThrows(NullPointerException.class, () -> IOUtils.buffer((Reader) null), npeExpectedMessage);
206         assertThrows(NullPointerException.class, () -> IOUtils.buffer((Writer) null), npeExpectedMessage);
207     }
208 
209     @Test
testAsBufferedOutputStream()210     public void testAsBufferedOutputStream() {
211         final OutputStream is = new OutputStream() {
212             @Override
213             public void write(final int b) throws IOException {
214             }
215         };
216         final BufferedOutputStream bis = IOUtils.buffer(is);
217         assertNotSame(is, bis);
218         assertSame(bis, IOUtils.buffer(bis));
219     }
220 
221     @Test
testAsBufferedOutputStreamWithBufferSize()222     public void testAsBufferedOutputStreamWithBufferSize() {
223         final OutputStream os = new OutputStream() {
224             @Override
225             public void write(final int b) throws IOException {
226             }
227         };
228         final BufferedOutputStream bos = IOUtils.buffer(os, 2048);
229         assertNotSame(os, bos);
230         assertSame(bos, IOUtils.buffer(bos));
231         assertSame(bos, IOUtils.buffer(bos, 1024));
232     }
233 
234     @Test
testAsBufferedReader()235     public void testAsBufferedReader() {
236         final Reader is = new Reader() {
237             @Override
238             public void close() throws IOException {
239             }
240 
241             @Override
242             public int read(final char[] cbuf, final int off, final int len) throws IOException {
243                 return 0;
244             }
245         };
246         final BufferedReader bis = IOUtils.buffer(is);
247         assertNotSame(is, bis);
248         assertSame(bis, IOUtils.buffer(bis));
249     }
250 
251     @Test
testAsBufferedReaderWithBufferSize()252     public void testAsBufferedReaderWithBufferSize() {
253         final Reader r = new Reader() {
254             @Override
255             public void close() throws IOException {
256             }
257 
258             @Override
259             public int read(final char[] cbuf, final int off, final int len) throws IOException {
260                 return 0;
261             }
262         };
263         final BufferedReader br = IOUtils.buffer(r, 2048);
264         assertNotSame(r, br);
265         assertSame(br, IOUtils.buffer(br));
266         assertSame(br, IOUtils.buffer(br, 1024));
267     }
268 
269     @Test
testAsBufferedWriter()270     public void testAsBufferedWriter() {
271         final Writer nullWriter = NullWriter.INSTANCE;
272         final BufferedWriter bis = IOUtils.buffer(nullWriter);
273         assertNotSame(nullWriter, bis);
274         assertSame(bis, IOUtils.buffer(bis));
275     }
276 
277     @Test
testAsBufferedWriterWithBufferSize()278     public void testAsBufferedWriterWithBufferSize() {
279         final Writer nullWriter = NullWriter.INSTANCE;
280         final BufferedWriter bw = IOUtils.buffer(nullWriter, 2024);
281         assertNotSame(nullWriter, bw);
282         assertSame(bw, IOUtils.buffer(bw));
283         assertSame(bw, IOUtils.buffer(bw, 1024));
284     }
285 
286     @Test
testAsWriterAppendable()287     public void testAsWriterAppendable() throws IOException {
288         final Appendable a = new StringBuffer();
289         try (Writer w = IOUtils.writer(a)) {
290             assertNotSame(w, a);
291             assertEquals(AppendableWriter.class, w.getClass());
292             assertSame(w, IOUtils.writer(w));
293         }
294     }
295 
296     @Test
testAsWriterNull()297     public void testAsWriterNull() {
298         assertThrows(NullPointerException.class, () -> IOUtils.writer(null));
299     }
300 
301     @Test
testAsWriterStringBuilder()302     public void testAsWriterStringBuilder() throws IOException {
303         final Appendable a = new StringBuilder();
304         try (Writer w = IOUtils.writer(a)) {
305             assertNotSame(w, a);
306             assertEquals(StringBuilderWriter.class, w.getClass());
307             assertSame(w, IOUtils.writer(w));
308         }
309     }
310 
311     @Test
testByteArrayWithNegativeSize()312     public void testByteArrayWithNegativeSize() {
313         assertThrows(NegativeArraySizeException.class, () -> IOUtils.byteArray(-1));
314     }
315 
316     @Test
testClose()317     public void testClose() {
318         assertDoesNotThrow(() -> IOUtils.close((Closeable) null));
319         assertDoesNotThrow(() -> IOUtils.close(new StringReader("s")));
320         assertThrows(IOException.class, () -> IOUtils.close(new ThrowOnCloseReader(new StringReader("s"))));
321     }
322 
323     @Test
testCloseConsumer()324     public void testCloseConsumer() {
325         final Closeable nullCloseable = null;
326         assertDoesNotThrow(() -> IOUtils.close(nullCloseable, null)); // null consumer
327         assertDoesNotThrow(() -> IOUtils.close(new StringReader("s"), null)); // null consumer
328         assertDoesNotThrow(() -> IOUtils.close(new ThrowOnCloseReader(new StringReader("s")), null)); // null consumer
329 
330         final IOConsumer<IOException> nullConsumer = null; // null consumer doesn't throw
331         assertDoesNotThrow(() -> IOUtils.close(nullCloseable, nullConsumer));
332         assertDoesNotThrow(() -> IOUtils.close(new StringReader("s"), nullConsumer));
333         assertDoesNotThrow(() -> IOUtils.close(new ThrowOnCloseReader(new StringReader("s")), nullConsumer));
334 
335         final IOConsumer<IOException> silentConsumer = IOConsumer.noop(); // noop consumer doesn't throw
336         assertDoesNotThrow(() -> IOUtils.close(nullCloseable, silentConsumer));
337         assertDoesNotThrow(() -> IOUtils.close(new StringReader("s"), silentConsumer));
338         assertDoesNotThrow(() -> IOUtils.close(new ThrowOnCloseReader(new StringReader("s")), silentConsumer));
339 
340         final IOConsumer<IOException> noisyConsumer = i -> {
341             throw i;
342         }; // consumer passes on the throw
343         assertDoesNotThrow(() -> IOUtils.close(nullCloseable, noisyConsumer)); // no throw
344         assertDoesNotThrow(() -> IOUtils.close(new StringReader("s"), noisyConsumer)); // no throw
345         assertThrows(IOException.class,
346             () -> IOUtils.close(new ThrowOnCloseReader(new StringReader("s")), noisyConsumer)); // closeable throws
347     }
348 
349     @Test
testCloseMulti()350     public void testCloseMulti() {
351         final Closeable nullCloseable = null;
352         final Closeable[] closeables = {null, null};
353         assertDoesNotThrow(() -> IOUtils.close(nullCloseable, nullCloseable));
354         assertDoesNotThrow(() -> IOUtils.close(closeables));
355         assertDoesNotThrow(() -> IOUtils.close((Closeable[]) null));
356         assertDoesNotThrow(() -> IOUtils.close(new StringReader("s"), nullCloseable));
357         assertThrows(IOException.class, () -> IOUtils.close(nullCloseable, new ThrowOnCloseReader(new StringReader("s"))));
358     }
359 
360     @Test
testCloseQuietly_AllCloseableIOException()361     public void testCloseQuietly_AllCloseableIOException() {
362         final Closeable closeable = BrokenInputStream.INSTANCE;
363         assertDoesNotThrow(() -> IOUtils.closeQuietly(closeable, null, closeable));
364         assertDoesNotThrow(() -> IOUtils.closeQuietly(Arrays.asList(closeable, null, closeable)));
365         assertDoesNotThrow(() -> IOUtils.closeQuietly(Stream.of(closeable, null, closeable)));
366         assertDoesNotThrow(() -> IOUtils.closeQuietly((Iterable<Closeable>) null));
367     }
368 
369     @Test
testCloseQuietly_CloseableIOException()370     public void testCloseQuietly_CloseableIOException() {
371         assertDoesNotThrow(() -> {
372             IOUtils.closeQuietly(BrokenInputStream.INSTANCE);
373         });
374         assertDoesNotThrow(() -> {
375             IOUtils.closeQuietly(BrokenOutputStream.INSTANCE);
376         });
377     }
378 
379     @SuppressWarnings("squid:S2699") // Suppress "Add at least one assertion to this test case"
380     @Test
testCloseQuietly_Selector()381     public void testCloseQuietly_Selector() {
382         Selector selector = null;
383         try {
384             selector = Selector.open();
385         } catch (final IOException ignore) {
386         } finally {
387             IOUtils.closeQuietly(selector);
388         }
389     }
390 
391     @SuppressWarnings("squid:S2699") // Suppress "Add at least one assertion to this test case"
392     @Test
testCloseQuietly_SelectorIOException()393     public void testCloseQuietly_SelectorIOException() {
394         final Selector selector = new SelectorAdapter() {
395             @Override
396             public void close() throws IOException {
397                 throw new IOException();
398             }
399         };
400         IOUtils.closeQuietly(selector);
401     }
402 
403     @SuppressWarnings("squid:S2699") // Suppress "Add at least one assertion to this test case"
404     @Test
testCloseQuietly_SelectorNull()405     public void testCloseQuietly_SelectorNull() {
406         final Selector selector = null;
407         IOUtils.closeQuietly(selector);
408     }
409 
410     @SuppressWarnings("squid:S2699") // Suppress "Add at least one assertion to this test case"
411     @Test
testCloseQuietly_SelectorTwice()412     public void testCloseQuietly_SelectorTwice() {
413         Selector selector = null;
414         try {
415             selector = Selector.open();
416         } catch (final IOException ignore) {
417         } finally {
418             IOUtils.closeQuietly(selector);
419             IOUtils.closeQuietly(selector);
420         }
421     }
422 
423     @Test
testCloseQuietly_ServerSocket()424     public void testCloseQuietly_ServerSocket() {
425         assertDoesNotThrow(() -> IOUtils.closeQuietly((ServerSocket) null));
426         assertDoesNotThrow(() -> IOUtils.closeQuietly(new ServerSocket()));
427     }
428 
429     @Test
testCloseQuietly_ServerSocketIOException()430     public void testCloseQuietly_ServerSocketIOException() {
431         assertDoesNotThrow(() -> {
432             IOUtils.closeQuietly(new ServerSocket() {
433                 @Override
434                 public void close() throws IOException {
435                     throw new IOException();
436                 }
437             });
438         });
439     }
440 
441     @Test
testCloseQuietly_Socket()442     public void testCloseQuietly_Socket() {
443         assertDoesNotThrow(() -> IOUtils.closeQuietly((Socket) null));
444         assertDoesNotThrow(() -> IOUtils.closeQuietly(new Socket()));
445     }
446 
447     @Test
testCloseQuietly_SocketIOException()448     public void testCloseQuietly_SocketIOException() {
449         assertDoesNotThrow(() -> {
450             IOUtils.closeQuietly(new Socket() {
451                 @Override
452                 public synchronized void close() throws IOException {
453                     throw new IOException();
454                 }
455             });
456         });
457     }
458 
459     @Test
testCloseURLConnection()460     public void testCloseURLConnection() {
461         assertDoesNotThrow(() -> IOUtils.close((URLConnection) null));
462         assertDoesNotThrow(() -> IOUtils.close(new URL("https://www.apache.org/").openConnection()));
463         assertDoesNotThrow(() -> IOUtils.close(new URL("file:///").openConnection()));
464     }
465 
466     @Test
testConstants()467     public void testConstants() {
468         assertEquals('/', IOUtils.DIR_SEPARATOR_UNIX);
469         assertEquals('\\', IOUtils.DIR_SEPARATOR_WINDOWS);
470         assertEquals("\n", IOUtils.LINE_SEPARATOR_UNIX);
471         assertEquals("\r\n", IOUtils.LINE_SEPARATOR_WINDOWS);
472         if (WINDOWS) {
473             assertEquals('\\', IOUtils.DIR_SEPARATOR);
474             assertEquals("\r\n", IOUtils.LINE_SEPARATOR);
475         } else {
476             assertEquals('/', IOUtils.DIR_SEPARATOR);
477             assertEquals("\n", IOUtils.LINE_SEPARATOR);
478         }
479         assertEquals('\r', IOUtils.CR);
480         assertEquals('\n', IOUtils.LF);
481         assertEquals(-1, IOUtils.EOF);
482     }
483 
484     @Test
testConsumeInputStream()485     public void testConsumeInputStream() throws Exception {
486         final long size = (long) Integer.MAX_VALUE + (long) 1;
487         final InputStream in = new NullInputStream(size);
488         final OutputStream out = NullOutputStream.INSTANCE;
489 
490         // Test copy() method
491         assertEquals(-1, IOUtils.copy(in, out));
492 
493         // reset the input
494         in.close();
495 
496         // Test consume() method
497         assertEquals(size, IOUtils.consume(in), "consume()");
498     }
499 
500     @Test
testConsumeReader()501     public void testConsumeReader() throws Exception {
502         final long size = (long) Integer.MAX_VALUE + (long) 1;
503         final Reader in = new NullReader(size);
504         final Writer out = NullWriter.INSTANCE;
505 
506         // Test copy() method
507         assertEquals(-1, IOUtils.copy(in, out));
508 
509         // reset the input
510         in.close();
511 
512         // Test consume() method
513         assertEquals(size, IOUtils.consume(in), "consume()");
514     }
515 
516     @Test
testContentEquals_InputStream_InputStream()517     public void testContentEquals_InputStream_InputStream() throws Exception {
518         {
519             assertTrue(IOUtils.contentEquals((InputStream) null, null));
520         }
521         final byte[] dataEmpty = "".getBytes(StandardCharsets.UTF_8);
522         final byte[] dataAbc = "ABC".getBytes(StandardCharsets.UTF_8);
523         final byte[] dataAbcd = "ABCD".getBytes(StandardCharsets.UTF_8);
524         {
525             final ByteArrayInputStream input1 = new ByteArrayInputStream(dataEmpty);
526             assertFalse(IOUtils.contentEquals(input1, null));
527         }
528         {
529             final ByteArrayInputStream input1 = new ByteArrayInputStream(dataEmpty);
530             assertFalse(IOUtils.contentEquals(null, input1));
531         }
532         {
533             final ByteArrayInputStream input1 = new ByteArrayInputStream(dataEmpty);
534             assertTrue(IOUtils.contentEquals(input1, input1));
535         }
536         {
537             final ByteArrayInputStream input1 = new ByteArrayInputStream(dataAbc);
538             assertTrue(IOUtils.contentEquals(input1, input1));
539         }
540         assertTrue(IOUtils.contentEquals(new ByteArrayInputStream(dataEmpty), new ByteArrayInputStream(dataEmpty)));
541         assertTrue(IOUtils.contentEquals(new BufferedInputStream(new ByteArrayInputStream(dataEmpty)),
542             new BufferedInputStream(new ByteArrayInputStream(dataEmpty))));
543         assertTrue(IOUtils.contentEquals(new ByteArrayInputStream(dataAbc), new ByteArrayInputStream(dataAbc)));
544         assertFalse(IOUtils.contentEquals(new ByteArrayInputStream(dataAbcd), new ByteArrayInputStream(dataAbc)));
545         assertFalse(IOUtils.contentEquals(new ByteArrayInputStream(dataAbc), new ByteArrayInputStream(dataAbcd)));
546         assertFalse(IOUtils.contentEquals(new ByteArrayInputStream("apache".getBytes(StandardCharsets.UTF_8)),
547                 new ByteArrayInputStream("apacha".getBytes(StandardCharsets.UTF_8))));
548         // Tests with larger inputs that DEFAULT_BUFFER_SIZE in case internal buffers are used.
549         final byte[] bytes2XDefaultA = new byte[IOUtils.DEFAULT_BUFFER_SIZE * 2];
550         final byte[] bytes2XDefaultB = new byte[IOUtils.DEFAULT_BUFFER_SIZE * 2];
551         final byte[] bytes2XDefaultA2 = new byte[IOUtils.DEFAULT_BUFFER_SIZE * 2];
552         Arrays.fill(bytes2XDefaultA, (byte) 'a');
553         Arrays.fill(bytes2XDefaultB, (byte) 'b');
554         Arrays.fill(bytes2XDefaultA2, (byte) 'a');
555         bytes2XDefaultA2[bytes2XDefaultA2.length - 1] = 'd';
556         assertFalse(IOUtils.contentEquals(new ByteArrayInputStream(bytes2XDefaultA),
557             new ByteArrayInputStream(bytes2XDefaultB)));
558         assertFalse(IOUtils.contentEquals(new ByteArrayInputStream(bytes2XDefaultA),
559             new ByteArrayInputStream(bytes2XDefaultA2)));
560         assertTrue(IOUtils.contentEquals(new ByteArrayInputStream(bytes2XDefaultA),
561             new ByteArrayInputStream(bytes2XDefaultA)));
562         // FileInputStream a bit more than 16 k.
563         try (
564             final FileInputStream input1 = new FileInputStream(
565                 "src/test/resources/org/apache/commons/io/abitmorethan16k.txt");
566             final FileInputStream input2 = new FileInputStream(
567                 "src/test/resources/org/apache/commons/io/abitmorethan16kcopy.txt")) {
568             assertTrue(IOUtils.contentEquals(input1, input1));
569         }
570     }
571 
572     @Test
testContentEquals_Reader_Reader()573     public void testContentEquals_Reader_Reader() throws Exception {
574         {
575             assertTrue(IOUtils.contentEquals((Reader) null, null));
576         }
577         {
578             final StringReader input1 = new StringReader("");
579             assertFalse(IOUtils.contentEquals(null, input1));
580         }
581         {
582             final StringReader input1 = new StringReader("");
583             assertFalse(IOUtils.contentEquals(input1, null));
584         }
585         {
586             final StringReader input1 = new StringReader("");
587             assertTrue(IOUtils.contentEquals(input1, input1));
588         }
589         {
590             final StringReader input1 = new StringReader("ABC");
591             assertTrue(IOUtils.contentEquals(input1, input1));
592         }
593         assertTrue(IOUtils.contentEquals(new StringReader(""), new StringReader("")));
594         assertTrue(
595             IOUtils.contentEquals(new BufferedReader(new StringReader("")), new BufferedReader(new StringReader(""))));
596         assertTrue(IOUtils.contentEquals(new StringReader("ABC"), new StringReader("ABC")));
597         assertFalse(IOUtils.contentEquals(new StringReader("ABCD"), new StringReader("ABC")));
598         assertFalse(IOUtils.contentEquals(new StringReader("ABC"), new StringReader("ABCD")));
599         assertFalse(IOUtils.contentEquals(new StringReader("apache"), new StringReader("apacha")));
600     }
601 
602     @Test
testContentEqualsIgnoreEOL()603     public void testContentEqualsIgnoreEOL() throws Exception {
604         {
605             assertTrue(IOUtils.contentEqualsIgnoreEOL(null, null));
606         }
607         final char[] empty = {};
608         {
609             final Reader input1 = new CharArrayReader(empty);
610             assertFalse(IOUtils.contentEqualsIgnoreEOL(null, input1));
611         }
612         {
613             final Reader input1 = new CharArrayReader(empty);
614             assertFalse(IOUtils.contentEqualsIgnoreEOL(input1, null));
615         }
616         {
617             final Reader input1 = new CharArrayReader(empty);
618             assertTrue(IOUtils.contentEqualsIgnoreEOL(input1, input1));
619         }
620         {
621             final Reader input1 = new CharArrayReader("321\r\n".toCharArray());
622             assertTrue(IOUtils.contentEqualsIgnoreEOL(input1, input1));
623         }
624 
625         testSingleEOL("", "", true);
626         testSingleEOL("", "\n", false);
627         testSingleEOL("", "\r", false);
628         testSingleEOL("", "\r\n", false);
629         testSingleEOL("", "\r\r", false);
630         testSingleEOL("", "\n\n", false);
631         testSingleEOL("1", "1", true);
632         testSingleEOL("1", "2", false);
633         testSingleEOL("123\rabc", "123\nabc", true);
634         testSingleEOL("321", "321\r\n", true);
635         testSingleEOL("321", "321\r\naabb", false);
636         testSingleEOL("321", "321\n", true);
637         testSingleEOL("321", "321\r", true);
638         testSingleEOL("321", "321\r\n", true);
639         testSingleEOL("321", "321\r\r", false);
640         testSingleEOL("321", "321\n\r", false);
641         testSingleEOL("321\n", "321", true);
642         testSingleEOL("321\n", "321\n\r", false);
643         testSingleEOL("321\n", "321\r\n", true);
644         testSingleEOL("321\r", "321\r\n", true);
645         testSingleEOL("321\r\n", "321\r\n\r", false);
646         testSingleEOL("123", "1234", false);
647         testSingleEOL("1235", "1234", false);
648     }
649 
650     @Test
testCopy_ByteArray_OutputStream()651     public void testCopy_ByteArray_OutputStream() throws Exception {
652         final File destination = TestUtils.newFile(temporaryFolder, "copy8.txt");
653         final byte[] in;
654         try (InputStream fin = Files.newInputStream(testFilePath)) {
655             // Create our byte[]. Rely on testInputStreamToByteArray() to make sure this is valid.
656             in = IOUtils.toByteArray(fin);
657         }
658 
659         try (OutputStream fout = Files.newOutputStream(destination.toPath())) {
660             CopyUtils.copy(in, fout);
661 
662             fout.flush();
663 
664             TestUtils.checkFile(destination, testFile);
665             TestUtils.checkWrite(fout);
666         }
667         TestUtils.deleteFile(destination);
668     }
669 
670     @Test
testCopy_ByteArray_Writer()671     public void testCopy_ByteArray_Writer() throws Exception {
672         final File destination = TestUtils.newFile(temporaryFolder, "copy7.txt");
673         final byte[] in;
674         try (InputStream fin = Files.newInputStream(testFilePath)) {
675             // Create our byte[]. Rely on testInputStreamToByteArray() to make sure this is valid.
676             in = IOUtils.toByteArray(fin);
677         }
678 
679         try (Writer fout = Files.newBufferedWriter(destination.toPath())) {
680             CopyUtils.copy(in, fout);
681             fout.flush();
682             TestUtils.checkFile(destination, testFile);
683             TestUtils.checkWrite(fout);
684         }
685         TestUtils.deleteFile(destination);
686     }
687 
688     @Test
testCopy_String_Writer()689     public void testCopy_String_Writer() throws Exception {
690         final File destination = TestUtils.newFile(temporaryFolder, "copy6.txt");
691         final String str;
692         try (Reader fin = Files.newBufferedReader(testFilePath)) {
693             // Create our String. Rely on testReaderToString() to make sure this is valid.
694             str = IOUtils.toString(fin);
695         }
696 
697         try (Writer fout = Files.newBufferedWriter(destination.toPath())) {
698             CopyUtils.copy(str, fout);
699             fout.flush();
700 
701             TestUtils.checkFile(destination, testFile);
702             TestUtils.checkWrite(fout);
703         }
704         TestUtils.deleteFile(destination);
705     }
706 
707     @Test
testCopyLarge_CharExtraLength()708     public void testCopyLarge_CharExtraLength() throws IOException {
709         CharArrayReader is = null;
710         CharArrayWriter os = null;
711         try {
712             // Create streams
713             is = new CharArrayReader(carr);
714             os = new CharArrayWriter();
715 
716             // Test our copy method
717             // for extra length, it reads till EOF
718             assertEquals(200, IOUtils.copyLarge(is, os, 0, 2000));
719             final char[] oarr = os.toCharArray();
720 
721             // check that output length is correct
722             assertEquals(200, oarr.length);
723             // check that output data corresponds to input data
724             assertEquals(1, oarr[1]);
725             assertEquals(79, oarr[79]);
726             assertEquals((char) -1, oarr[80]);
727 
728         } finally {
729             IOUtils.closeQuietly(is);
730             IOUtils.closeQuietly(os);
731         }
732     }
733 
734     @Test
testCopyLarge_CharFullLength()735     public void testCopyLarge_CharFullLength() throws IOException {
736         CharArrayReader is = null;
737         CharArrayWriter os = null;
738         try {
739             // Create streams
740             is = new CharArrayReader(carr);
741             os = new CharArrayWriter();
742 
743             // Test our copy method
744             assertEquals(200, IOUtils.copyLarge(is, os, 0, -1));
745             final char[] oarr = os.toCharArray();
746 
747             // check that output length is correct
748             assertEquals(200, oarr.length);
749             // check that output data corresponds to input data
750             assertEquals(1, oarr[1]);
751             assertEquals(79, oarr[79]);
752             assertEquals((char) -1, oarr[80]);
753 
754         } finally {
755             IOUtils.closeQuietly(is);
756             IOUtils.closeQuietly(os);
757         }
758     }
759 
760     @Test
testCopyLarge_CharNoSkip()761     public void testCopyLarge_CharNoSkip() throws IOException {
762         CharArrayReader is = null;
763         CharArrayWriter os = null;
764         try {
765             // Create streams
766             is = new CharArrayReader(carr);
767             os = new CharArrayWriter();
768 
769             // Test our copy method
770             assertEquals(100, IOUtils.copyLarge(is, os, 0, 100));
771             final char[] oarr = os.toCharArray();
772 
773             // check that output length is correct
774             assertEquals(100, oarr.length);
775             // check that output data corresponds to input data
776             assertEquals(1, oarr[1]);
777             assertEquals(79, oarr[79]);
778             assertEquals((char) -1, oarr[80]);
779 
780         } finally {
781             IOUtils.closeQuietly(is);
782             IOUtils.closeQuietly(os);
783         }
784     }
785 
786     @Test
testCopyLarge_CharSkip()787     public void testCopyLarge_CharSkip() throws IOException {
788         CharArrayReader is = null;
789         CharArrayWriter os = null;
790         try {
791             // Create streams
792             is = new CharArrayReader(carr);
793             os = new CharArrayWriter();
794 
795             // Test our copy method
796             assertEquals(100, IOUtils.copyLarge(is, os, 10, 100));
797             final char[] oarr = os.toCharArray();
798 
799             // check that output length is correct
800             assertEquals(100, oarr.length);
801             // check that output data corresponds to input data
802             assertEquals(11, oarr[1]);
803             assertEquals(79, oarr[69]);
804             assertEquals((char) -1, oarr[70]);
805 
806         } finally {
807             IOUtils.closeQuietly(is);
808             IOUtils.closeQuietly(os);
809         }
810     }
811 
812     @Test
testCopyLarge_CharSkipInvalid()813     public void testCopyLarge_CharSkipInvalid() {
814         try (CharArrayReader is = new CharArrayReader(carr); CharArrayWriter os = new CharArrayWriter()) {
815             assertThrows(EOFException.class, () -> IOUtils.copyLarge(is, os, 1000, 100));
816         }
817     }
818 
819     @Test
testCopyLarge_ExtraLength()820     public void testCopyLarge_ExtraLength() throws IOException {
821         try (ByteArrayInputStream is = new ByteArrayInputStream(iarr);
822             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
823             // Create streams
824 
825             // Test our copy method
826             // for extra length, it reads till EOF
827             assertEquals(200, IOUtils.copyLarge(is, os, 0, 2000));
828             final byte[] oarr = os.toByteArray();
829 
830             // check that output length is correct
831             assertEquals(200, oarr.length);
832             // check that output data corresponds to input data
833             assertEquals(1, oarr[1]);
834             assertEquals(79, oarr[79]);
835             assertEquals(-1, oarr[80]);
836         }
837     }
838 
839     @Test
testCopyLarge_FullLength()840     public void testCopyLarge_FullLength() throws IOException {
841         try (ByteArrayInputStream is = new ByteArrayInputStream(iarr);
842             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
843             // Test our copy method
844             assertEquals(200, IOUtils.copyLarge(is, os, 0, -1));
845             final byte[] oarr = os.toByteArray();
846 
847             // check that output length is correct
848             assertEquals(200, oarr.length);
849             // check that output data corresponds to input data
850             assertEquals(1, oarr[1]);
851             assertEquals(79, oarr[79]);
852             assertEquals(-1, oarr[80]);
853         }
854     }
855 
856     @Test
testCopyLarge_NoSkip()857     public void testCopyLarge_NoSkip() throws IOException {
858         try (ByteArrayInputStream is = new ByteArrayInputStream(iarr);
859             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
860             // Test our copy method
861             assertEquals(100, IOUtils.copyLarge(is, os, 0, 100));
862             final byte[] oarr = os.toByteArray();
863 
864             // check that output length is correct
865             assertEquals(100, oarr.length);
866             // check that output data corresponds to input data
867             assertEquals(1, oarr[1]);
868             assertEquals(79, oarr[79]);
869             assertEquals(-1, oarr[80]);
870         }
871     }
872 
873     @Test
testCopyLarge_Skip()874     public void testCopyLarge_Skip() throws IOException {
875         try (ByteArrayInputStream is = new ByteArrayInputStream(iarr);
876             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
877             // Test our copy method
878             assertEquals(100, IOUtils.copyLarge(is, os, 10, 100));
879             final byte[] oarr = os.toByteArray();
880 
881             // check that output length is correct
882             assertEquals(100, oarr.length);
883             // check that output data corresponds to input data
884             assertEquals(11, oarr[1]);
885             assertEquals(79, oarr[69]);
886             assertEquals(-1, oarr[70]);
887         }
888     }
889 
890     @Test
testCopyLarge_SkipInvalid()891     public void testCopyLarge_SkipInvalid() throws IOException {
892         try (ByteArrayInputStream is = new ByteArrayInputStream(iarr);
893             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
894             // Test our copy method
895             assertThrows(EOFException.class, () -> IOUtils.copyLarge(is, os, 1000, 100));
896         }
897     }
898 
899     @Test
testCopyLarge_SkipWithInvalidOffset()900     public void testCopyLarge_SkipWithInvalidOffset() throws IOException {
901         ByteArrayInputStream is = null;
902         ByteArrayOutputStream os = null;
903         try {
904             // Create streams
905             is = new ByteArrayInputStream(iarr);
906             os = new ByteArrayOutputStream();
907 
908             // Test our copy method
909             assertEquals(100, IOUtils.copyLarge(is, os, -10, 100));
910             final byte[] oarr = os.toByteArray();
911 
912             // check that output length is correct
913             assertEquals(100, oarr.length);
914             // check that output data corresponds to input data
915             assertEquals(1, oarr[1]);
916             assertEquals(79, oarr[79]);
917             assertEquals(-1, oarr[80]);
918 
919         } finally {
920             IOUtils.closeQuietly(is);
921             IOUtils.closeQuietly(os);
922         }
923     }
924 
925     @Test
testRead_ReadableByteChannel()926     public void testRead_ReadableByteChannel() throws Exception {
927         final ByteBuffer buffer = ByteBuffer.allocate(FILE_SIZE);
928         final FileInputStream fileInputStream = new FileInputStream(testFile);
929         final FileChannel input = fileInputStream.getChannel();
930         try {
931             assertEquals(FILE_SIZE, IOUtils.read(input, buffer));
932             assertEquals(0, IOUtils.read(input, buffer));
933             assertEquals(0, buffer.remaining());
934             assertEquals(0, input.read(buffer));
935             buffer.clear();
936             assertThrows(EOFException.class, () -> IOUtils.readFully(input, buffer), "Should have failed with EOFException");
937         } finally {
938             IOUtils.closeQuietly(input, fileInputStream);
939         }
940     }
941 
942     @Test
testReadFully_InputStream__ReturnByteArray()943     public void testReadFully_InputStream__ReturnByteArray() throws Exception {
944         final byte[] bytes = "abcd1234".getBytes(StandardCharsets.UTF_8);
945         final ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
946 
947         final byte[] result = IOUtils.readFully(stream, bytes.length);
948 
949         IOUtils.closeQuietly(stream);
950 
951         assertEqualContent(result, bytes);
952     }
953 
954     @Test
testReadFully_InputStream_ByteArray()955     public void testReadFully_InputStream_ByteArray() throws Exception {
956         final int size = 1027;
957         final byte[] buffer = new byte[size];
958         final InputStream input = new ByteArrayInputStream(new byte[size]);
959 
960         assertThrows(IllegalArgumentException.class, () -> IOUtils.readFully(input, buffer, 0, -1), "Should have failed with IllegalArgumentException");
961 
962         IOUtils.readFully(input, buffer, 0, 0);
963         IOUtils.readFully(input, buffer, 0, size - 1);
964         assertThrows(EOFException.class, () -> IOUtils.readFully(input, buffer, 0, 2), "Should have failed with EOFException");
965         IOUtils.closeQuietly(input);
966     }
967 
968     @Test
testReadFully_InputStream_Offset()969     public void testReadFully_InputStream_Offset() throws Exception {
970         final InputStream stream = CharSequenceInputStream.builder().setCharSequence("abcd1234").setCharset(StandardCharsets.UTF_8).get();
971         final byte[] buffer = "wx00000000".getBytes(StandardCharsets.UTF_8);
972         IOUtils.readFully(stream, buffer, 2, 8);
973         assertEquals("wxabcd1234", new String(buffer, 0, buffer.length, StandardCharsets.UTF_8));
974         IOUtils.closeQuietly(stream);
975     }
976 
977     @Test
testReadFully_ReadableByteChannel()978     public void testReadFully_ReadableByteChannel() throws Exception {
979         final ByteBuffer buffer = ByteBuffer.allocate(FILE_SIZE);
980         final FileInputStream fileInputStream = new FileInputStream(testFile);
981         final FileChannel input = fileInputStream.getChannel();
982         try {
983             IOUtils.readFully(input, buffer);
984             assertEquals(FILE_SIZE, buffer.position());
985             assertEquals(0, buffer.remaining());
986             assertEquals(0, input.read(buffer));
987             IOUtils.readFully(input, buffer);
988             assertEquals(FILE_SIZE, buffer.position());
989             assertEquals(0, buffer.remaining());
990             assertEquals(0, input.read(buffer));
991             IOUtils.readFully(input, buffer);
992             buffer.clear();
993             assertThrows(EOFException.class, () -> IOUtils.readFully(input, buffer), "Should have failed with EOFxception");
994         } finally {
995             IOUtils.closeQuietly(input, fileInputStream);
996         }
997     }
998 
999     @Test
testReadFully_Reader()1000     public void testReadFully_Reader() throws Exception {
1001         final int size = 1027;
1002         final char[] buffer = new char[size];
1003         final Reader input = new CharArrayReader(new char[size]);
1004 
1005         IOUtils.readFully(input, buffer, 0, 0);
1006         IOUtils.readFully(input, buffer, 0, size - 3);
1007         assertThrows(IllegalArgumentException.class, () -> IOUtils.readFully(input, buffer, 0, -1), "Should have failed with IllegalArgumentException");
1008         assertThrows(EOFException.class, () -> IOUtils.readFully(input, buffer, 0, 5), "Should have failed with EOFException");
1009         IOUtils.closeQuietly(input);
1010     }
1011 
1012     @Test
testReadFully_Reader_Offset()1013     public void testReadFully_Reader_Offset() throws Exception {
1014         final Reader reader = new StringReader("abcd1234");
1015         final char[] buffer = "wx00000000".toCharArray();
1016         IOUtils.readFully(reader, buffer, 2, 8);
1017         assertEquals("wxabcd1234", new String(buffer));
1018         IOUtils.closeQuietly(reader);
1019     }
1020 
1021     @Test
testReadLines_InputStream()1022     public void testReadLines_InputStream() throws Exception {
1023         final File file = TestUtils.newFile(temporaryFolder, "lines.txt");
1024         InputStream in = null;
1025         try {
1026             final String[] data = {"hello", "world", "", "this is", "some text"};
1027             TestUtils.createLineBasedFile(file, data);
1028 
1029             in = Files.newInputStream(file.toPath());
1030             final List<String> lines = IOUtils.readLines(in);
1031             assertEquals(Arrays.asList(data), lines);
1032             assertEquals(-1, in.read());
1033         } finally {
1034             IOUtils.closeQuietly(in);
1035             TestUtils.deleteFile(file);
1036         }
1037     }
1038 
1039     @Test
testReadLines_InputStream_String()1040     public void testReadLines_InputStream_String() throws Exception {
1041         final File file = TestUtils.newFile(temporaryFolder, "lines.txt");
1042         InputStream in = null;
1043         try {
1044             final String[] data = {"hello", "/u1234", "", "this is", "some text"};
1045             TestUtils.createLineBasedFile(file, data);
1046 
1047             in = Files.newInputStream(file.toPath());
1048             final List<String> lines = IOUtils.readLines(in, UTF_8);
1049             assertEquals(Arrays.asList(data), lines);
1050             assertEquals(-1, in.read());
1051         } finally {
1052             IOUtils.closeQuietly(in);
1053             TestUtils.deleteFile(file);
1054         }
1055     }
1056 
1057     @Test
testReadLines_Reader()1058     public void testReadLines_Reader() throws Exception {
1059         final File file = TestUtils.newFile(temporaryFolder, "lines.txt");
1060         Reader in = null;
1061         try {
1062             final String[] data = {"hello", "/u1234", "", "this is", "some text"};
1063             TestUtils.createLineBasedFile(file, data);
1064 
1065             in = new InputStreamReader(Files.newInputStream(file.toPath()));
1066             final List<String> lines = IOUtils.readLines(in);
1067             assertEquals(Arrays.asList(data), lines);
1068             assertEquals(-1, in.read());
1069         } finally {
1070             IOUtils.closeQuietly(in);
1071             TestUtils.deleteFile(file);
1072         }
1073     }
1074 
1075     @Test
testResourceToByteArray_ExistingResourceAtRootPackage()1076     public void testResourceToByteArray_ExistingResourceAtRootPackage() throws Exception {
1077         final long fileSize = TestResources.getFile("test-file-utf8.bin").length();
1078         final byte[] bytes = IOUtils.resourceToByteArray("/org/apache/commons/io/test-file-utf8.bin");
1079         assertNotNull(bytes);
1080         assertEquals(fileSize, bytes.length);
1081     }
1082 
1083     @Test
testResourceToByteArray_ExistingResourceAtRootPackage_WithClassLoader()1084     public void testResourceToByteArray_ExistingResourceAtRootPackage_WithClassLoader() throws Exception {
1085         final long fileSize = TestResources.getFile("test-file-utf8.bin").length();
1086         final byte[] bytes = IOUtils.resourceToByteArray("org/apache/commons/io/test-file-utf8.bin",
1087             ClassLoader.getSystemClassLoader());
1088         assertNotNull(bytes);
1089         assertEquals(fileSize, bytes.length);
1090     }
1091 
1092     @Test
testResourceToByteArray_ExistingResourceAtSubPackage()1093     public void testResourceToByteArray_ExistingResourceAtSubPackage() throws Exception {
1094         final long fileSize = TestResources.getFile("FileUtilsTestDataCR.dat").length();
1095         final byte[] bytes = IOUtils.resourceToByteArray("/org/apache/commons/io/FileUtilsTestDataCR.dat");
1096         assertNotNull(bytes);
1097         assertEquals(fileSize, bytes.length);
1098     }
1099 
1100     @Test
testResourceToByteArray_ExistingResourceAtSubPackage_WithClassLoader()1101     public void testResourceToByteArray_ExistingResourceAtSubPackage_WithClassLoader() throws Exception {
1102         final long fileSize = TestResources.getFile("FileUtilsTestDataCR.dat").length();
1103         final byte[] bytes = IOUtils.resourceToByteArray("org/apache/commons/io/FileUtilsTestDataCR.dat",
1104             ClassLoader.getSystemClassLoader());
1105         assertNotNull(bytes);
1106         assertEquals(fileSize, bytes.length);
1107     }
1108 
1109     @Test
testResourceToByteArray_NonExistingResource()1110     public void testResourceToByteArray_NonExistingResource() {
1111         assertThrows(IOException.class, () -> IOUtils.resourceToByteArray("/non-existing-file.bin"));
1112     }
1113 
1114     @Test
testResourceToByteArray_NonExistingResource_WithClassLoader()1115     public void testResourceToByteArray_NonExistingResource_WithClassLoader() {
1116         assertThrows(IOException.class,
1117             () -> IOUtils.resourceToByteArray("non-existing-file.bin", ClassLoader.getSystemClassLoader()));
1118     }
1119 
1120     @Test
testResourceToByteArray_Null()1121     public void testResourceToByteArray_Null() {
1122         assertThrows(NullPointerException.class, () -> IOUtils.resourceToByteArray(null));
1123     }
1124 
1125     @Test
testResourceToByteArray_Null_WithClassLoader()1126     public void testResourceToByteArray_Null_WithClassLoader() {
1127         assertThrows(NullPointerException.class,
1128             () -> IOUtils.resourceToByteArray(null, ClassLoader.getSystemClassLoader()));
1129     }
1130 
1131     @Test
testResourceToString_ExistingResourceAtRootPackage()1132     public void testResourceToString_ExistingResourceAtRootPackage() throws Exception {
1133         final long fileSize = TestResources.getFile("test-file-simple-utf8.bin").length();
1134         final String content = IOUtils.resourceToString("/org/apache/commons/io/test-file-simple-utf8.bin",
1135             StandardCharsets.UTF_8);
1136 
1137         assertNotNull(content);
1138         assertEquals(fileSize, content.getBytes().length);
1139     }
1140 
1141     @Test
testResourceToString_ExistingResourceAtRootPackage_WithClassLoader()1142     public void testResourceToString_ExistingResourceAtRootPackage_WithClassLoader() throws Exception {
1143         final long fileSize = TestResources.getFile("test-file-simple-utf8.bin").length();
1144         final String content = IOUtils.resourceToString("org/apache/commons/io/test-file-simple-utf8.bin",
1145             StandardCharsets.UTF_8, ClassLoader.getSystemClassLoader());
1146 
1147         assertNotNull(content);
1148         assertEquals(fileSize, content.getBytes().length);
1149     }
1150 
1151     @Test
testResourceToString_ExistingResourceAtSubPackage()1152     public void testResourceToString_ExistingResourceAtSubPackage() throws Exception {
1153         final long fileSize = TestResources.getFile("FileUtilsTestDataCR.dat").length();
1154         final String content = IOUtils.resourceToString("/org/apache/commons/io/FileUtilsTestDataCR.dat",
1155             StandardCharsets.UTF_8);
1156 
1157         assertNotNull(content);
1158         assertEquals(fileSize, content.getBytes().length);
1159     }
1160 
1161     // Tests from IO-305
1162 
1163     @Test
testResourceToString_ExistingResourceAtSubPackage_WithClassLoader()1164     public void testResourceToString_ExistingResourceAtSubPackage_WithClassLoader() throws Exception {
1165         final long fileSize = TestResources.getFile("FileUtilsTestDataCR.dat").length();
1166         final String content = IOUtils.resourceToString("org/apache/commons/io/FileUtilsTestDataCR.dat",
1167             StandardCharsets.UTF_8, ClassLoader.getSystemClassLoader());
1168 
1169         assertNotNull(content);
1170         assertEquals(fileSize, content.getBytes().length);
1171     }
1172 
1173     @Test
testResourceToString_NonExistingResource()1174     public void testResourceToString_NonExistingResource() {
1175         assertThrows(IOException.class,
1176             () -> IOUtils.resourceToString("/non-existing-file.bin", StandardCharsets.UTF_8));
1177     }
1178 
1179     @Test
testResourceToString_NonExistingResource_WithClassLoader()1180     public void testResourceToString_NonExistingResource_WithClassLoader() {
1181         assertThrows(IOException.class, () -> IOUtils.resourceToString("non-existing-file.bin", StandardCharsets.UTF_8,
1182             ClassLoader.getSystemClassLoader()));
1183     }
1184 
1185     @SuppressWarnings("squid:S2699") // Suppress "Add at least one assertion to this test case"
1186     @Test
testResourceToString_NullCharset()1187     public void testResourceToString_NullCharset() throws Exception {
1188         IOUtils.resourceToString("/org/apache/commons/io//test-file-utf8.bin", null);
1189     }
1190 
1191     @SuppressWarnings("squid:S2699") // Suppress "Add at least one assertion to this test case"
1192     @Test
testResourceToString_NullCharset_WithClassLoader()1193     public void testResourceToString_NullCharset_WithClassLoader() throws Exception {
1194         IOUtils.resourceToString("org/apache/commons/io/test-file-utf8.bin", null, ClassLoader.getSystemClassLoader());
1195     }
1196 
1197     @Test
testResourceToString_NullResource()1198     public void testResourceToString_NullResource() {
1199         assertThrows(NullPointerException.class, () -> IOUtils.resourceToString(null, StandardCharsets.UTF_8));
1200     }
1201 
1202     @Test
testResourceToString_NullResource_WithClassLoader()1203     public void testResourceToString_NullResource_WithClassLoader() {
1204         assertThrows(NullPointerException.class,
1205             () -> IOUtils.resourceToString(null, StandardCharsets.UTF_8, ClassLoader.getSystemClassLoader()));
1206     }
1207 
1208     @Test
testResourceToURL_ExistingResourceAtRootPackage()1209     public void testResourceToURL_ExistingResourceAtRootPackage() throws Exception {
1210         final URL url = IOUtils.resourceToURL("/org/apache/commons/io/test-file-utf8.bin");
1211         assertNotNull(url);
1212         assertTrue(url.getFile().endsWith("/test-file-utf8.bin"));
1213     }
1214 
1215     @Test
testResourceToURL_ExistingResourceAtRootPackage_WithClassLoader()1216     public void testResourceToURL_ExistingResourceAtRootPackage_WithClassLoader() throws Exception {
1217         final URL url = IOUtils.resourceToURL("org/apache/commons/io/test-file-utf8.bin",
1218             ClassLoader.getSystemClassLoader());
1219         assertNotNull(url);
1220         assertTrue(url.getFile().endsWith("/org/apache/commons/io/test-file-utf8.bin"));
1221     }
1222 
1223     @Test
testResourceToURL_ExistingResourceAtSubPackage()1224     public void testResourceToURL_ExistingResourceAtSubPackage() throws Exception {
1225         final URL url = IOUtils.resourceToURL("/org/apache/commons/io/FileUtilsTestDataCR.dat");
1226         assertNotNull(url);
1227         assertTrue(url.getFile().endsWith("/org/apache/commons/io/FileUtilsTestDataCR.dat"));
1228     }
1229 
1230     @Test
testResourceToURL_ExistingResourceAtSubPackage_WithClassLoader()1231     public void testResourceToURL_ExistingResourceAtSubPackage_WithClassLoader() throws Exception {
1232         final URL url = IOUtils.resourceToURL("org/apache/commons/io/FileUtilsTestDataCR.dat",
1233             ClassLoader.getSystemClassLoader());
1234 
1235         assertNotNull(url);
1236         assertTrue(url.getFile().endsWith("/org/apache/commons/io/FileUtilsTestDataCR.dat"));
1237     }
1238 
1239     @Test
testResourceToURL_NonExistingResource()1240     public void testResourceToURL_NonExistingResource() {
1241         assertThrows(IOException.class, () -> IOUtils.resourceToURL("/non-existing-file.bin"));
1242     }
1243 
1244     @Test
testResourceToURL_NonExistingResource_WithClassLoader()1245     public void testResourceToURL_NonExistingResource_WithClassLoader() {
1246         assertThrows(IOException.class,
1247             () -> IOUtils.resourceToURL("non-existing-file.bin", ClassLoader.getSystemClassLoader()));
1248     }
1249 
1250     @Test
testResourceToURL_Null()1251     public void testResourceToURL_Null() {
1252         assertThrows(NullPointerException.class, () -> IOUtils.resourceToURL(null));
1253     }
1254 
1255     @Test
testResourceToURL_Null_WithClassLoader()1256     public void testResourceToURL_Null_WithClassLoader() {
1257         assertThrows(NullPointerException.class, () -> IOUtils.resourceToURL(null, ClassLoader.getSystemClassLoader()));
1258     }
1259 
testSingleEOL(final String s1, final String s2, final boolean ifEquals)1260     public void testSingleEOL(final String s1, final String s2, final boolean ifEquals) {
1261         assertEquals(ifEquals, IOUtils.contentEqualsIgnoreEOL(
1262                 new CharArrayReader(s1.toCharArray()),
1263                 new CharArrayReader(s2.toCharArray())
1264         ), "failed at :{" + s1 + "," + s2 + "}");
1265         assertEquals(ifEquals, IOUtils.contentEqualsIgnoreEOL(
1266                 new CharArrayReader(s2.toCharArray()),
1267                 new CharArrayReader(s1.toCharArray())
1268         ), "failed at :{" + s2 + "," + s1 + "}");
1269         assertTrue(IOUtils.contentEqualsIgnoreEOL(
1270                 new CharArrayReader(s1.toCharArray()),
1271                 new CharArrayReader(s1.toCharArray())
1272         ),"failed at :{" + s1 + "," + s1 + "}");
1273         assertTrue(IOUtils.contentEqualsIgnoreEOL(
1274                 new CharArrayReader(s2.toCharArray()),
1275                 new CharArrayReader(s2.toCharArray())
1276         ), "failed at :{" + s2 + "," + s2 + "}");
1277     }
1278 
1279     @Test
testSkip_FileReader()1280     public void testSkip_FileReader() throws Exception {
1281         try (Reader in = Files.newBufferedReader(testFilePath)) {
1282             assertEquals(FILE_SIZE - 10, IOUtils.skip(in, FILE_SIZE - 10));
1283             assertEquals(10, IOUtils.skip(in, 20));
1284             assertEquals(0, IOUtils.skip(in, 10));
1285         }
1286     }
1287 
1288     @Test
testSkip_InputStream()1289     public void testSkip_InputStream() throws Exception {
1290         try (InputStream in = Files.newInputStream(testFilePath)) {
1291             assertEquals(FILE_SIZE - 10, IOUtils.skip(in, FILE_SIZE - 10));
1292             assertEquals(10, IOUtils.skip(in, 20));
1293             assertEquals(0, IOUtils.skip(in, 10));
1294         }
1295     }
1296 
1297     @Test
testSkip_ReadableByteChannel()1298     public void testSkip_ReadableByteChannel() throws Exception {
1299         final FileInputStream fileInputStream = new FileInputStream(testFile);
1300         final FileChannel fileChannel = fileInputStream.getChannel();
1301         try {
1302             assertEquals(FILE_SIZE - 10, IOUtils.skip(fileChannel, FILE_SIZE - 10));
1303             assertEquals(10, IOUtils.skip(fileChannel, 20));
1304             assertEquals(0, IOUtils.skip(fileChannel, 10));
1305         } finally {
1306             IOUtils.closeQuietly(fileChannel, fileInputStream);
1307         }
1308     }
1309 
1310     @Test
testSkipFully_InputStream()1311     public void testSkipFully_InputStream() throws Exception {
1312         final int size = 1027;
1313 
1314         try (final InputStream input = new ByteArrayInputStream(new byte[size])) {
1315             assertThrows(IllegalArgumentException.class, () -> IOUtils.skipFully(input, -1), "Should have failed with IllegalArgumentException");
1316 
1317             IOUtils.skipFully(input, 0);
1318             IOUtils.skipFully(input, size - 1);
1319             assertThrows(IOException.class, () -> IOUtils.skipFully(input, 2), "Should have failed with IOException");
1320         }
1321     }
1322 
1323     @Test
testSkipFully_InputStream_Buffer_New_bytes()1324     public void testSkipFully_InputStream_Buffer_New_bytes() throws Exception {
1325         final int size = 1027;
1326         final Supplier<byte[]> bas = () -> new byte[size];
1327         try (final InputStream input = new ByteArrayInputStream(new byte[size])) {
1328             assertThrows(IllegalArgumentException.class, () -> IOUtils.skipFully(input, -1, bas), "Should have failed with IllegalArgumentException");
1329 
1330             IOUtils.skipFully(input, 0, bas);
1331             IOUtils.skipFully(input, size - 1, bas);
1332             assertThrows(IOException.class, () -> IOUtils.skipFully(input, 2, bas), "Should have failed with IOException");
1333         }
1334     }
1335 
1336     @Test
testSkipFully_InputStream_Buffer_Reuse_bytes()1337     public void testSkipFully_InputStream_Buffer_Reuse_bytes() throws Exception {
1338         final int size = 1027;
1339         final byte[] ba = new byte[size];
1340         final Supplier<byte[]> bas = () -> ba;
1341         try (final InputStream input = new ByteArrayInputStream(new byte[size])) {
1342             assertThrows(IllegalArgumentException.class, () -> IOUtils.skipFully(input, -1, bas), "Should have failed with IllegalArgumentException");
1343 
1344             IOUtils.skipFully(input, 0, bas);
1345             IOUtils.skipFully(input, size - 1, bas);
1346             assertThrows(IOException.class, () -> IOUtils.skipFully(input, 2, bas), "Should have failed with IOException");
1347         }
1348     }
1349 
1350     @Test
testSkipFully_InputStream_Buffer_Reuse_ThreadLocal()1351     public void testSkipFully_InputStream_Buffer_Reuse_ThreadLocal() throws Exception {
1352         final int size = 1027;
1353         final ThreadLocal<byte[]> tl = ThreadLocal.withInitial(() -> new byte[size]);
1354         try (final InputStream input = new ByteArrayInputStream(new byte[size])) {
1355             assertThrows(IllegalArgumentException.class, () -> IOUtils.skipFully(input, -1, tl::get), "Should have failed with IllegalArgumentException");
1356 
1357             IOUtils.skipFully(input, 0, tl::get);
1358             IOUtils.skipFully(input, size - 1, tl::get);
1359             assertThrows(IOException.class, () -> IOUtils.skipFully(input, 2, tl::get), "Should have failed with IOException");
1360         }
1361     }
1362 
1363     @Test
testSkipFully_ReadableByteChannel()1364     public void testSkipFully_ReadableByteChannel() throws Exception {
1365         final FileInputStream fileInputStream = new FileInputStream(testFile);
1366         final FileChannel fileChannel = fileInputStream.getChannel();
1367         try {
1368             assertThrows(IllegalArgumentException.class, () -> IOUtils.skipFully(fileChannel, -1), "Should have failed with IllegalArgumentException");
1369             IOUtils.skipFully(fileChannel, 0);
1370             IOUtils.skipFully(fileChannel, FILE_SIZE - 1);
1371             assertThrows(IOException.class, () -> IOUtils.skipFully(fileChannel, 2), "Should have failed with IOException");
1372         } finally {
1373             IOUtils.closeQuietly(fileChannel, fileInputStream);
1374         }
1375     }
1376 
1377     @Test
testSkipFully_Reader()1378     public void testSkipFully_Reader() throws Exception {
1379         final int size = 1027;
1380         try (final Reader input = new CharArrayReader(new char[size])) {
1381             IOUtils.skipFully(input, 0);
1382             IOUtils.skipFully(input, size - 3);
1383             assertThrows(IllegalArgumentException.class, () -> IOUtils.skipFully(input, -1), "Should have failed with IllegalArgumentException");
1384             assertThrows(IOException.class, () -> IOUtils.skipFully(input, 5), "Should have failed with IOException");
1385         }
1386     }
1387 
1388     @Test
testStringToOutputStream()1389     public void testStringToOutputStream() throws Exception {
1390         final File destination = TestUtils.newFile(temporaryFolder, "copy5.txt");
1391         final String str;
1392         try (Reader fin = Files.newBufferedReader(testFilePath)) {
1393             // Create our String. Rely on testReaderToString() to make sure this is valid.
1394             str = IOUtils.toString(fin);
1395         }
1396 
1397         try (OutputStream fout = Files.newOutputStream(destination.toPath())) {
1398             CopyUtils.copy(str, fout);
1399             // Note: this method *does* flush. It is equivalent to:
1400             // OutputStreamWriter _out = new OutputStreamWriter(fout);
1401             // CopyUtils.copy( str, _out, 4096 ); // copy( Reader, Writer, int );
1402             // _out.flush();
1403             // out = fout;
1404             // note: we don't flush here; this IOUtils method does it for us
1405 
1406             TestUtils.checkFile(destination, testFile);
1407             TestUtils.checkWrite(fout);
1408         }
1409         TestUtils.deleteFile(destination);
1410     }
1411 
1412     @Test
testToBufferedInputStream_InputStream()1413     public void testToBufferedInputStream_InputStream() throws Exception {
1414         try (InputStream fin = Files.newInputStream(testFilePath)) {
1415             final InputStream in = IOUtils.toBufferedInputStream(fin);
1416             final byte[] out = IOUtils.toByteArray(in);
1417             assertNotNull(out);
1418             assertEquals(0, fin.available(), "Not all bytes were read");
1419             assertEquals(FILE_SIZE, out.length, "Wrong output size");
1420             TestUtils.assertEqualContent(out, testFile);
1421         }
1422     }
1423 
1424     @Test
testToBufferedInputStreamWithBufferSize_InputStream()1425     public void testToBufferedInputStreamWithBufferSize_InputStream() throws Exception {
1426         try (InputStream fin = Files.newInputStream(testFilePath)) {
1427             final InputStream in = IOUtils.toBufferedInputStream(fin, 2048);
1428             final byte[] out = IOUtils.toByteArray(in);
1429             assertNotNull(out);
1430             assertEquals(0, fin.available(), "Not all bytes were read");
1431             assertEquals(FILE_SIZE, out.length, "Wrong output size");
1432             TestUtils.assertEqualContent(out, testFile);
1433         }
1434     }
1435 
1436     @Test
testToByteArray_InputStream()1437     public void testToByteArray_InputStream() throws Exception {
1438         try (InputStream fin = Files.newInputStream(testFilePath)) {
1439             final byte[] out = IOUtils.toByteArray(fin);
1440             assertNotNull(out);
1441             assertEquals(0, fin.available(), "Not all bytes were read");
1442             assertEquals(FILE_SIZE, out.length, "Wrong output size");
1443             TestUtils.assertEqualContent(out, testFile);
1444         }
1445     }
1446 
1447     @Test
1448     @Disabled("Disable by default as it uses too much memory and can cause builds to fail.")
testToByteArray_InputStream_LongerThanIntegerMaxValue()1449     public void testToByteArray_InputStream_LongerThanIntegerMaxValue() throws Exception {
1450         final CircularInputStream cin = new CircularInputStream(IOUtils.byteArray(), Integer.MAX_VALUE + 1L);
1451         assertThrows(IllegalArgumentException.class, () -> IOUtils.toByteArray(cin));
1452     }
1453 
1454     @Test
testToByteArray_InputStream_NegativeSize()1455     public void testToByteArray_InputStream_NegativeSize() throws Exception {
1456         try (InputStream fin = Files.newInputStream(testFilePath)) {
1457             final IllegalArgumentException exc = assertThrows(IllegalArgumentException.class, () -> IOUtils.toByteArray(fin, -1),
1458                     "Should have failed with IllegalArgumentException");
1459             assertTrue(exc.getMessage().startsWith("Size must be equal or greater than zero"),
1460                     "Exception message does not start with \"Size must be equal or greater than zero\"");
1461         }
1462     }
1463 
1464     @Test
testToByteArray_InputStream_Size()1465     public void testToByteArray_InputStream_Size() throws Exception {
1466         try (InputStream fin = Files.newInputStream(testFilePath)) {
1467             final byte[] out = IOUtils.toByteArray(fin, testFile.length());
1468             assertNotNull(out);
1469             assertEquals(0, fin.available(), "Not all bytes were read");
1470             assertEquals(FILE_SIZE, out.length, "Wrong output size: out.length=" + out.length + "!=" + FILE_SIZE);
1471             TestUtils.assertEqualContent(out, testFile);
1472         }
1473     }
1474 
1475     @Test
testToByteArray_InputStream_SizeIllegal()1476     public void testToByteArray_InputStream_SizeIllegal() throws Exception {
1477         try (InputStream fin = Files.newInputStream(testFilePath)) {
1478             final IOException exc = assertThrows(IOException.class, () -> IOUtils.toByteArray(fin, testFile.length() + 1),
1479                     "Should have failed with IOException");
1480             assertTrue(exc.getMessage().startsWith("Unexpected read size"), "Exception message does not start with \"Unexpected read size\"");
1481         }
1482     }
1483 
1484     @Test
testToByteArray_InputStream_SizeLong()1485     public void testToByteArray_InputStream_SizeLong() throws Exception {
1486         try (InputStream fin = Files.newInputStream(testFilePath)) {
1487             final IllegalArgumentException exc = assertThrows(IllegalArgumentException.class, () -> IOUtils.toByteArray(fin, (long) Integer.MAX_VALUE + 1),
1488                     "Should have failed with IllegalArgumentException");
1489             assertTrue(exc.getMessage().startsWith("Size cannot be greater than Integer max value"),
1490                     "Exception message does not start with \"Size cannot be greater than Integer max value\"");
1491         }
1492     }
1493 
1494     @Test
testToByteArray_InputStream_SizeOne()1495     public void testToByteArray_InputStream_SizeOne() throws Exception {
1496         try (InputStream fin = Files.newInputStream(testFilePath)) {
1497             final byte[] out = IOUtils.toByteArray(fin, 1);
1498             assertNotNull(out, "Out cannot be null");
1499             assertEquals(1, out.length, "Out length must be 1");
1500         }
1501     }
1502 
1503     @Test
testToByteArray_InputStream_SizeZero()1504     public void testToByteArray_InputStream_SizeZero() throws Exception {
1505         try (InputStream fin =Files.newInputStream(testFilePath)) {
1506             final byte[] out = IOUtils.toByteArray(fin, 0);
1507             assertNotNull(out, "Out cannot be null");
1508             assertEquals(0, out.length, "Out length must be 0");
1509         }
1510     }
1511 
1512     @Test
testToByteArray_Reader()1513     public void testToByteArray_Reader() throws IOException {
1514         final String charsetName = UTF_8;
1515         final byte[] expected = charsetName.getBytes(charsetName);
1516         byte[] actual = IOUtils.toByteArray(new InputStreamReader(new ByteArrayInputStream(expected)));
1517         assertArrayEquals(expected, actual);
1518         actual = IOUtils.toByteArray(new InputStreamReader(new ByteArrayInputStream(expected)), charsetName);
1519         assertArrayEquals(expected, actual);
1520     }
1521 
1522     @Test
testToByteArray_String()1523     public void testToByteArray_String() throws Exception {
1524         try (Reader fin = Files.newBufferedReader(testFilePath)) {
1525             // Create our String. Rely on testReaderToString() to make sure this is valid.
1526             final String str = IOUtils.toString(fin);
1527 
1528             final byte[] out = IOUtils.toByteArray(str);
1529             assertEqualContent(str.getBytes(), out);
1530         }
1531     }
1532 
1533     @Test
testToByteArray_URI()1534     public void testToByteArray_URI() throws Exception {
1535         final URI url = testFile.toURI();
1536         final byte[] actual = IOUtils.toByteArray(url);
1537         assertEquals(FILE_SIZE, actual.length);
1538     }
1539 
1540     @Test
testToByteArray_URL()1541     public void testToByteArray_URL() throws Exception {
1542         final URL url = testFile.toURI().toURL();
1543         final byte[] actual = IOUtils.toByteArray(url);
1544         assertEquals(FILE_SIZE, actual.length);
1545     }
1546 
1547     @Test
testToByteArray_URLConnection()1548     public void testToByteArray_URLConnection() throws Exception {
1549         final byte[] actual;
1550         try (CloseableURLConnection urlConnection = CloseableURLConnection.open(testFile.toURI())) {
1551             actual = IOUtils.toByteArray(urlConnection);
1552         }
1553         assertEquals(FILE_SIZE, actual.length);
1554     }
1555 
1556     @Test
testToCharArray_InputStream()1557     public void testToCharArray_InputStream() throws Exception {
1558         try (InputStream fin = Files.newInputStream(testFilePath)) {
1559             final char[] out = IOUtils.toCharArray(fin);
1560             assertNotNull(out);
1561             assertEquals(0, fin.available(), "Not all chars were read");
1562             assertEquals(FILE_SIZE, out.length, "Wrong output size");
1563             TestUtils.assertEqualContent(out, testFile);
1564         }
1565     }
1566 
1567     @Test
testToCharArray_InputStream_CharsetName()1568     public void testToCharArray_InputStream_CharsetName() throws Exception {
1569         try (InputStream fin = Files.newInputStream(testFilePath)) {
1570             final char[] out = IOUtils.toCharArray(fin, UTF_8);
1571             assertNotNull(out);
1572             assertEquals(0, fin.available(), "Not all chars were read");
1573             assertEquals(FILE_SIZE, out.length, "Wrong output size");
1574             TestUtils.assertEqualContent(out, testFile);
1575         }
1576     }
1577 
1578     @Test
testToCharArray_Reader()1579     public void testToCharArray_Reader() throws Exception {
1580         try (Reader fr = Files.newBufferedReader(testFilePath)) {
1581             final char[] out = IOUtils.toCharArray(fr);
1582             assertNotNull(out);
1583             assertEquals(FILE_SIZE, out.length, "Wrong output size");
1584             TestUtils.assertEqualContent(out, testFile);
1585         }
1586     }
1587 
1588     /**
1589      * Test for {@link IOUtils#toInputStream(CharSequence)} and {@link IOUtils#toInputStream(CharSequence, String)}.
1590      * Note, this test utilizes on {@link IOUtils#toByteArray(InputStream)} and so relies on
1591      * {@link #testToByteArray_InputStream()} to ensure this method functions correctly.
1592      *
1593      * @throws Exception on error
1594      */
1595     @Test
testToInputStream_CharSequence()1596     public void testToInputStream_CharSequence() throws Exception {
1597         final CharSequence csq = new StringBuilder("Abc123Xyz!");
1598         InputStream inStream = IOUtils.toInputStream(csq); // deliberately testing deprecated method
1599         byte[] bytes = IOUtils.toByteArray(inStream);
1600         assertEqualContent(csq.toString().getBytes(), bytes);
1601         inStream = IOUtils.toInputStream(csq, (String) null);
1602         bytes = IOUtils.toByteArray(inStream);
1603         assertEqualContent(csq.toString().getBytes(), bytes);
1604         inStream = IOUtils.toInputStream(csq, UTF_8);
1605         bytes = IOUtils.toByteArray(inStream);
1606         assertEqualContent(csq.toString().getBytes(StandardCharsets.UTF_8), bytes);
1607     }
1608 
1609     /**
1610      * Test for {@link IOUtils#toInputStream(String)} and {@link IOUtils#toInputStream(String, String)}. Note, this test
1611      * utilizes on {@link IOUtils#toByteArray(InputStream)} and so relies on
1612      * {@link #testToByteArray_InputStream()} to ensure this method functions correctly.
1613      *
1614      * @throws Exception on error
1615      */
1616     @Test
testToInputStream_String()1617     public void testToInputStream_String() throws Exception {
1618         final String str = "Abc123Xyz!";
1619         InputStream inStream = IOUtils.toInputStream(str);
1620         byte[] bytes = IOUtils.toByteArray(inStream);
1621         assertEqualContent(str.getBytes(), bytes);
1622         inStream = IOUtils.toInputStream(str, (String) null);
1623         bytes = IOUtils.toByteArray(inStream);
1624         assertEqualContent(str.getBytes(), bytes);
1625         inStream = IOUtils.toInputStream(str, UTF_8);
1626         bytes = IOUtils.toByteArray(inStream);
1627         assertEqualContent(str.getBytes(StandardCharsets.UTF_8), bytes);
1628     }
1629 
1630     @Test
testToString_ByteArray()1631     public void testToString_ByteArray() throws Exception {
1632         try (InputStream fin = Files.newInputStream(testFilePath)) {
1633             final byte[] in = IOUtils.toByteArray(fin);
1634             // Create our byte[]. Rely on testInputStreamToByteArray() to make sure this is valid.
1635             final String str = IOUtils.toString(in);
1636             assertEqualContent(in, str.getBytes());
1637         }
1638     }
1639 
1640     @Test
testToString_InputStream()1641     public void testToString_InputStream() throws Exception {
1642         try (InputStream fin = Files.newInputStream(testFilePath)) {
1643             final String out = IOUtils.toString(fin);
1644             assertNotNull(out);
1645             assertEquals(0, fin.available(), "Not all bytes were read");
1646             assertEquals(FILE_SIZE, out.length(), "Wrong output size");
1647         }
1648     }
1649 
1650     @Test
testToString_InputStreamSupplier()1651     public void testToString_InputStreamSupplier() throws Exception {
1652         final String out = IOUtils.toString(() -> Files.newInputStream(testFilePath), Charset.defaultCharset());
1653         assertNotNull(out);
1654         assertEquals(FILE_SIZE, out.length(), "Wrong output size");
1655         assertNull(IOUtils.toString(null, Charset.defaultCharset(), () -> null));
1656         assertNull(IOUtils.toString(() -> null, Charset.defaultCharset(), () -> null));
1657         assertEquals("A", IOUtils.toString(null, Charset.defaultCharset(), () -> "A"));
1658     }
1659 
1660     @Test
testToString_Reader()1661     public void testToString_Reader() throws Exception {
1662         try (Reader fin = Files.newBufferedReader(testFilePath)) {
1663             final String out = IOUtils.toString(fin);
1664             assertNotNull(out);
1665             assertEquals(FILE_SIZE, out.length(), "Wrong output size");
1666         }
1667     }
1668 
1669     @Test
testToString_URI()1670     public void testToString_URI() throws Exception {
1671         final URI url = testFile.toURI();
1672         final String out = IOUtils.toString(url);
1673         assertNotNull(out);
1674         assertEquals(FILE_SIZE, out.length(), "Wrong output size");
1675     }
1676 
testToString_URI(final String encoding)1677     private void testToString_URI(final String encoding) throws Exception {
1678         final URI uri = testFile.toURI();
1679         final String out = IOUtils.toString(uri, encoding);
1680         assertNotNull(out);
1681         assertEquals(FILE_SIZE, out.length(), "Wrong output size");
1682     }
1683 
1684     @Test
testToString_URI_CharsetName()1685     public void testToString_URI_CharsetName() throws Exception {
1686         testToString_URI("US-ASCII");
1687     }
1688 
1689     @Test
testToString_URI_CharsetNameNull()1690     public void testToString_URI_CharsetNameNull() throws Exception {
1691         testToString_URI(null);
1692     }
1693 
1694     @Test
testToString_URL()1695     public void testToString_URL() throws Exception {
1696         final URL url = testFile.toURI().toURL();
1697         final String out = IOUtils.toString(url);
1698         assertNotNull(out);
1699         assertEquals(FILE_SIZE, out.length(), "Wrong output size");
1700     }
1701 
testToString_URL(final String encoding)1702     private void testToString_URL(final String encoding) throws Exception {
1703         final URL url = testFile.toURI().toURL();
1704         final String out = IOUtils.toString(url, encoding);
1705         assertNotNull(out);
1706         assertEquals(FILE_SIZE, out.length(), "Wrong output size");
1707     }
1708 
1709     @Test
testToString_URL_CharsetName()1710     public void testToString_URL_CharsetName() throws Exception {
1711         testToString_URL("US-ASCII");
1712     }
1713 
1714     @Test
testToString_URL_CharsetNameNull()1715     public void testToString_URL_CharsetNameNull() throws Exception {
1716         testToString_URL(null);
1717     }
1718 
1719     /**
1720      * IO-764 IOUtils.write() throws NegativeArraySizeException while writing big strings.
1721      * <pre>
1722      * java.lang.OutOfMemoryError: Java heap space
1723      *     at java.lang.StringCoding.encode(StringCoding.java:350)
1724      *     at java.lang.String.getBytes(String.java:941)
1725      *     at org.apache.commons.io.IOUtils.write(IOUtils.java:3367)
1726      *     at org.apache.commons.io.IOUtilsTest.testBigString(IOUtilsTest.java:1659)
1727      * </pre>
1728      */
1729     @Test
testWriteBigString()1730     public void testWriteBigString() throws IOException {
1731         // 3_000_000 is a size that we can allocate for the test string with Java 8 on the command line as:
1732         // mvn clean test -Dtest=IOUtilsTest -DtestBigString=3000000
1733         // 6_000_000 failed with the above
1734         //
1735         // TODO Can we mock the test string for this test to pretend to be larger?
1736         // Mocking the length seems simple but how about the data?
1737         final int repeat = Integer.getInteger("testBigString", 3_000_000);
1738         final String data;
1739         try {
1740             data = StringUtils.repeat("\uD83D", repeat);
1741         } catch (final OutOfMemoryError e) {
1742             System.err.printf("Don't fail the test if we cannot build the fixture, just log, fixture size = %,d%n.", repeat);
1743             e.printStackTrace();
1744             return;
1745         }
1746         try (CountingOutputStream os = new CountingOutputStream(NullOutputStream.INSTANCE)) {
1747             IOUtils.write(data, os, StandardCharsets.UTF_8);
1748             assertEquals(repeat, os.getByteCount());
1749         }
1750     }
1751 
1752     @Test
testWriteLines()1753     public void testWriteLines() throws IOException {
1754         final String[] data = {"The", "quick"};
1755         final ByteArrayOutputStream out = new ByteArrayOutputStream();
1756         IOUtils.writeLines(Arrays.asList(data), "\n", out, "UTF-16");
1757         final String result = new String(out.toByteArray(), StandardCharsets.UTF_16);
1758         assertEquals("The\nquick\n", result);
1759     }
1760 
1761     @Test
testWriteLittleString()1762     public void testWriteLittleString() throws IOException {
1763         final String data = "\uD83D";
1764         // White-box test to check that not closing the internal channel is not a problem.
1765         for (int i = 0; i < 1_000_000; i++) {
1766             try (CountingOutputStream os = new CountingOutputStream(NullOutputStream.INSTANCE)) {
1767                 IOUtils.write(data, os, StandardCharsets.UTF_8);
1768                 assertEquals(data.length(), os.getByteCount());
1769             }
1770         }
1771     }
1772 
1773 }
1774