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