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.assertEquals; 21 import static org.junit.jupiter.api.Assertions.assertFalse; 22 import static org.junit.jupiter.api.Assertions.assertNotEquals; 23 import static org.junit.jupiter.api.Assertions.assertNotNull; 24 import static org.junit.jupiter.api.Assertions.assertNull; 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 import static org.junit.jupiter.api.Assertions.fail; 29 30 import java.io.BufferedOutputStream; 31 import java.io.ByteArrayOutputStream; 32 import java.io.File; 33 import java.io.FileInputStream; 34 import java.io.FileNotFoundException; 35 import java.io.FileOutputStream; 36 import java.io.IOException; 37 import java.io.InputStream; 38 import java.io.OutputStream; 39 import java.math.BigInteger; 40 import java.net.URL; 41 import java.nio.charset.Charset; 42 import java.nio.charset.StandardCharsets; 43 import java.nio.file.Files; 44 import java.nio.file.Path; 45 import java.nio.file.Paths; 46 import java.nio.file.StandardCopyOption; 47 import java.nio.file.attribute.FileTime; 48 import java.time.Instant; 49 import java.time.LocalDate; 50 import java.time.LocalDateTime; 51 import java.time.LocalTime; 52 import java.time.OffsetDateTime; 53 import java.time.OffsetTime; 54 import java.time.ZoneId; 55 import java.time.ZoneOffset; 56 import java.time.ZonedDateTime; 57 import java.util.ArrayList; 58 import java.util.Arrays; 59 import java.util.Collection; 60 import java.util.Collections; 61 import java.util.Date; 62 import java.util.GregorianCalendar; 63 import java.util.HashMap; 64 import java.util.Iterator; 65 import java.util.List; 66 import java.util.Map; 67 import java.util.Set; 68 import java.util.concurrent.TimeUnit; 69 import java.util.stream.Collectors; 70 import java.util.zip.CRC32; 71 import java.util.zip.Checksum; 72 73 import org.apache.commons.io.file.AbstractTempDirTest; 74 import org.apache.commons.io.file.PathUtils; 75 import org.apache.commons.io.file.PathUtilsIsEmptyTest; 76 import org.apache.commons.io.file.TempDirectory; 77 import org.apache.commons.io.file.TempFile; 78 import org.apache.commons.io.filefilter.IOFileFilter; 79 import org.apache.commons.io.filefilter.NameFileFilter; 80 import org.apache.commons.io.filefilter.WildcardFileFilter; 81 import org.apache.commons.io.test.TestUtils; 82 import org.apache.commons.lang3.SystemUtils; 83 import org.junit.jupiter.api.Assertions; 84 import org.junit.jupiter.api.BeforeEach; 85 import org.junit.jupiter.api.Disabled; 86 import org.junit.jupiter.api.Test; 87 import org.junit.jupiter.params.ParameterizedTest; 88 import org.junit.jupiter.params.provider.ValueSource; 89 90 /** 91 * This is used to test FileUtils for correctness. 92 * 93 * @see FileUtils 94 */ 95 @SuppressWarnings({"deprecation", "ResultOfMethodCallIgnored"}) // unit tests include tests of many deprecated methods 96 public class FileUtilsTest extends AbstractTempDirTest { 97 98 /** 99 * DirectoryWalker implementation that recursively lists all files and directories. 100 */ 101 static class ListDirectoryWalker extends DirectoryWalker<File> { 102 ListDirectoryWalker()103 ListDirectoryWalker() { 104 } 105 106 @Override handleDirectoryStart(final File directory, final int depth, final Collection<File> results)107 protected void handleDirectoryStart(final File directory, final int depth, final Collection<File> results) throws IOException { 108 // Add all directories except the starting directory 109 if (depth > 0) { 110 results.add(directory); 111 } 112 } 113 114 @Override handleFile(final File file, final int depth, final Collection<File> results)115 protected void handleFile(final File file, final int depth, final Collection<File> results) throws IOException { 116 results.add(file); 117 } 118 list(final File startDirectory)119 List<File> list(final File startDirectory) throws IOException { 120 final ArrayList<File> files = new ArrayList<>(); 121 walk(startDirectory, files); 122 return files; 123 } 124 } 125 126 // Test helper class to pretend a file is shorter than it is 127 private static class ShorterFile extends File { 128 private static final long serialVersionUID = 1L; 129 ShorterFile(final String pathname)130 public ShorterFile(final String pathname) { 131 super(pathname); 132 } 133 134 @Override length()135 public long length() { 136 return super.length() - 1; 137 } 138 } 139 140 private static final String UTF_8 = StandardCharsets.UTF_8.name(); 141 142 /** Test data. */ 143 private static final long DATE3 = 1000000002000L; 144 145 /** Test data. */ 146 private static final long DATE2 = 1000000001000L; 147 148 /** Test data. */ 149 private static final long DATE1 = 1000000000000L; 150 151 /** 152 * Size of test directory. 153 */ 154 private static final int TEST_DIRECTORY_SIZE = 0; 155 156 /** 157 * Size of test directory. 158 */ 159 private static final BigInteger TEST_DIRECTORY_SIZE_BI = BigInteger.ZERO; 160 161 /** 162 * Size (greater of zero) of test file. 163 */ 164 private static final BigInteger TEST_DIRECTORY_SIZE_GT_ZERO_BI = BigInteger.valueOf(100); 165 166 /** 167 * List files recursively 168 */ 169 private static final ListDirectoryWalker LIST_WALKER = new ListDirectoryWalker(); 170 171 /** 172 * Delay in milliseconds to make sure test for "last modified date" are accurate 173 */ 174 //private static final int LAST_MODIFIED_DELAY = 600; 175 176 private File testFile1; 177 private File testFile2; 178 179 private long testFile1Size; 180 181 private long testFile2Size; 182 assertContentMatchesAfterCopyURLToFileFor(final String resourceName, final File destination)183 private void assertContentMatchesAfterCopyURLToFileFor(final String resourceName, final File destination) throws IOException { 184 FileUtils.copyURLToFile(getClass().getResource(resourceName), destination); 185 186 try (InputStream fis = Files.newInputStream(destination.toPath()); 187 InputStream expected = getClass().getResourceAsStream(resourceName)) { 188 assertTrue(IOUtils.contentEquals(expected, fis), "Content is not equal."); 189 } 190 } 191 backDateFile10Minutes(final File testFile)192 private void backDateFile10Minutes(final File testFile) throws IOException { 193 final long mins10 = 1000 * 60 * 10; 194 final long lastModified1 = getLastModifiedMillis(testFile); 195 assertTrue(setLastModifiedMillis(testFile, lastModified1 - mins10)); 196 // ensure it was changed 197 assertNotEquals(getLastModifiedMillis(testFile), lastModified1, "Should have changed source date"); 198 } 199 consumeRemaining(final Iterator<File> iterator)200 private void consumeRemaining(final Iterator<File> iterator) { 201 if (iterator != null) { 202 iterator.forEachRemaining(e -> {}); 203 } 204 } 205 createCircularOsSymLink(final String linkName, final String targetName)206 private Path createCircularOsSymLink(final String linkName, final String targetName) throws IOException { 207 return Files.createSymbolicLink(Paths.get(linkName), Paths.get(targetName)); 208 } 209 210 /** 211 * May throw java.nio.file.FileSystemException: C:\Users\...\FileUtilsTestCase\cycle: A required privilege is not held 212 * by the client. On Windows, you are fine if you run a terminal with admin karma. 213 */ createCircularSymLink(final File file)214 private void createCircularSymLink(final File file) throws IOException { 215 assertTrue(file.exists()); 216 final String linkName = file + "/cycle"; 217 final String targetName = file + "/.."; 218 assertTrue(file.exists()); 219 final Path linkPath = Paths.get(linkName); 220 assertFalse(Files.exists(linkPath)); 221 final Path targetPath = Paths.get(targetName); 222 assertTrue(Files.exists(targetPath)); 223 try { 224 // May throw java.nio.file.FileSystemException: C:\Users\...\FileUtilsTestCase\cycle: A required privilege is not held by the client. 225 // On Windows, you are fine if you run a terminal with admin karma. 226 Files.createSymbolicLink(linkPath, targetPath); 227 } catch (final UnsupportedOperationException e) { 228 e.printStackTrace(); 229 createCircularOsSymLink(linkName, targetName); 230 } 231 // Sanity check: 232 assertTrue(Files.isSymbolicLink(linkPath), () -> "Expected a sym link here: " + linkName); 233 } 234 createFilesForTestCopyDirectory(final File grandParentDir, final File parentDir, final File childDir)235 private void createFilesForTestCopyDirectory(final File grandParentDir, final File parentDir, final File childDir) throws IOException { 236 final File childDir2 = new File(parentDir, "child2"); 237 final File grandChildDir = new File(childDir, "grandChild"); 238 final File grandChild2Dir = new File(childDir2, "grandChild2"); 239 final File file1 = new File(grandParentDir, "file1.txt"); 240 final File file2 = new File(parentDir, "file2.txt"); 241 final File file3 = new File(childDir, "file3.txt"); 242 final File file4 = new File(childDir2, "file4.txt"); 243 final File file5 = new File(grandChildDir, "file5.txt"); 244 final File file6 = new File(grandChild2Dir, "file6.txt"); 245 FileUtils.deleteDirectory(grandParentDir); 246 grandChildDir.mkdirs(); 247 grandChild2Dir.mkdirs(); 248 FileUtils.writeStringToFile(file1, "File 1 in grandparent", "UTF8"); 249 FileUtils.writeStringToFile(file2, "File 2 in parent", "UTF8"); 250 FileUtils.writeStringToFile(file3, "File 3 in child", "UTF8"); 251 FileUtils.writeStringToFile(file4, "File 4 in child2", "UTF8"); 252 FileUtils.writeStringToFile(file5, "File 5 in grandChild", "UTF8"); 253 FileUtils.writeStringToFile(file6, "File 6 in grandChild2", "UTF8"); 254 } 255 createTempSymlinkedRelativeDir()256 private Path createTempSymlinkedRelativeDir() throws IOException { 257 final Path targetDir = tempDirPath.resolve("subdir"); 258 final Path symlinkDir = tempDirPath.resolve("symlinked-dir"); 259 Files.createDirectory(targetDir); 260 Files.createSymbolicLink(symlinkDir, targetDir); 261 return symlinkDir; 262 } 263 getFilePathSet(final List<File> files)264 private Set<String> getFilePathSet(final List<File> files) { 265 return files.stream().map(f -> { 266 try { 267 return f.getCanonicalPath(); 268 } catch (IOException e) { 269 throw new RuntimeException(e); 270 } 271 }).collect(Collectors.toSet()); 272 } 273 274 private long getLastModifiedMillis(final File file) throws IOException { 275 return FileUtils.lastModified(file); 276 } 277 278 private String getName() { 279 return this.getClass().getSimpleName(); 280 } 281 282 private void iterateFilesAndDirs(final File dir, final IOFileFilter fileFilter, 283 final IOFileFilter dirFilter, final Collection<File> expectedFilesAndDirs) { 284 final Iterator<File> iterator; 285 int filesCount = 0; 286 iterator = FileUtils.iterateFilesAndDirs(dir, fileFilter, dirFilter); 287 try { 288 final List<File> actualFiles = new ArrayList<>(); 289 while (iterator.hasNext()) { 290 filesCount++; 291 final File file = iterator.next(); 292 actualFiles.add(file); 293 assertTrue(expectedFilesAndDirs.contains(file), 294 () -> "Unexpected directory/file " + file + ", expected one of " + expectedFilesAndDirs); 295 } 296 assertEquals(expectedFilesAndDirs.size(), filesCount, actualFiles::toString); 297 } finally { 298 // MUST consume until the end in order to close the underlying stream. 299 consumeRemaining(iterator); 300 } 301 } 302 303 void openOutputStream_noParent(final boolean createFile) throws Exception { 304 final File file = new File("test.txt"); 305 assertNull(file.getParentFile()); 306 try { 307 if (createFile) { 308 TestUtils.createLineBasedFile(file, new String[]{"Hello"}); 309 } 310 try (FileOutputStream out = FileUtils.openOutputStream(file)) { 311 out.write(0); 312 } 313 assertTrue(file.exists()); 314 } finally { 315 if (!file.delete()) { 316 file.deleteOnExit(); 317 } 318 } 319 } 320 321 private boolean setLastModifiedMillis(final File testFile, final long millis) { 322 return testFile.setLastModified(millis); 323 // try { 324 // Files.setLastModifiedTime(testFile.toPath(), FileTime.fromMillis(millis)); 325 // } catch (IOException e) { 326 // return false; 327 // } 328 // return true; 329 } 330 331 @BeforeEach 332 public void setUp() throws Exception { 333 testFile1 = new File(tempDirFile, "file1-test.txt"); 334 testFile2 = new File(tempDirFile, "file1a-test.txt"); 335 336 testFile1Size = testFile1.length(); 337 testFile2Size = testFile2.length(); 338 if (!testFile1.getParentFile().exists()) { 339 fail("Cannot create file " + testFile1 340 + " as the parent directory does not exist"); 341 } 342 try (BufferedOutputStream output3 = 343 new BufferedOutputStream(Files.newOutputStream(testFile1.toPath()))) { 344 TestUtils.generateTestData(output3, testFile1Size); 345 } 346 if (!testFile2.getParentFile().exists()) { 347 fail("Cannot create file " + testFile2 348 + " as the parent directory does not exist"); 349 } 350 try (BufferedOutputStream output2 = 351 new BufferedOutputStream(Files.newOutputStream(testFile2.toPath()))) { 352 TestUtils.generateTestData(output2, testFile2Size); 353 } 354 FileUtils.deleteDirectory(tempDirFile); 355 tempDirFile.mkdirs(); 356 if (!testFile1.getParentFile().exists()) { 357 fail("Cannot create file " + testFile1 358 + " as the parent directory does not exist"); 359 } 360 try (BufferedOutputStream output1 = 361 new BufferedOutputStream(Files.newOutputStream(testFile1.toPath()))) { 362 TestUtils.generateTestData(output1, testFile1Size); 363 } 364 if (!testFile2.getParentFile().exists()) { 365 fail("Cannot create file " + testFile2 366 + " as the parent directory does not exist"); 367 } 368 try (BufferedOutputStream output = 369 new BufferedOutputStream(Files.newOutputStream(testFile2.toPath()))) { 370 TestUtils.generateTestData(output, testFile2Size); 371 } 372 } 373 374 @Test 375 public void test_openInputStream_exists() throws Exception { 376 final File file = new File(tempDirFile, "test.txt"); 377 TestUtils.createLineBasedFile(file, new String[]{"Hello"}); 378 try (FileInputStream in = FileUtils.openInputStream(file)) { 379 assertEquals('H', in.read()); 380 } 381 } 382 383 @Test 384 public void test_openInputStream_existsButIsDirectory() { 385 final File directory = new File(tempDirFile, "subdir"); 386 directory.mkdirs(); 387 assertThrows(IOException.class, () -> FileUtils.openInputStream(directory)); 388 } 389 390 @Test 391 public void test_openInputStream_notExists() { 392 final File directory = new File(tempDirFile, "test.txt"); 393 assertThrows(IOException.class, () -> FileUtils.openInputStream(directory)); 394 } 395 396 @Test 397 public void test_openOutputStream_exists() throws Exception { 398 final File file = new File(tempDirFile, "test.txt"); 399 TestUtils.createLineBasedFile(file, new String[]{"Hello"}); 400 try (FileOutputStream out = FileUtils.openOutputStream(file)) { 401 out.write(0); 402 } 403 assertTrue(file.exists()); 404 } 405 406 @Test 407 public void test_openOutputStream_existsButIsDirectory() { 408 final File directory = new File(tempDirFile, "subdir"); 409 directory.mkdirs(); 410 assertThrows(IllegalArgumentException.class, () -> FileUtils.openOutputStream(directory)); 411 } 412 413 @Test 414 public void test_openOutputStream_intoExistingSymlinkedDir() throws Exception { 415 final Path symlinkedDir = createTempSymlinkedRelativeDir(); 416 417 final File file = symlinkedDir.resolve("test.txt").toFile(); 418 try (FileOutputStream out = FileUtils.openOutputStream(file)) { 419 out.write(0); 420 } 421 assertTrue(file.exists()); 422 } 423 424 @Test 425 public void test_openOutputStream_noParentCreateFile() throws Exception { 426 openOutputStream_noParent(true); 427 } 428 429 @Test 430 public void test_openOutputStream_noParentNoFile() throws Exception { 431 openOutputStream_noParent(false); 432 } 433 434 @Test 435 public void test_openOutputStream_notExists() throws Exception { 436 final File file = new File(tempDirFile, "a/test.txt"); 437 try (FileOutputStream out = FileUtils.openOutputStream(file)) { 438 out.write(0); 439 } 440 assertTrue(file.exists()); 441 } 442 443 @Test 444 public void test_openOutputStream_notExistsCannotCreate() { 445 // according to Wikipedia, most filing systems have a 256 limit on filename 446 final String longStr = 447 "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" + 448 "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" + 449 "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" + 450 "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" + 451 "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" + 452 "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz"; // 300 chars 453 final File file = new File(tempDirFile, "a/" + longStr + "/test.txt"); 454 assertThrows(IOException.class, () -> FileUtils.openOutputStream(file)); 455 } 456 457 // byteCountToDisplaySize 458 @Test 459 public void testByteCountToDisplaySizeBigInteger() { 460 final BigInteger b1023 = BigInteger.valueOf(1023); 461 final BigInteger b1025 = BigInteger.valueOf(1025); 462 final BigInteger KB1 = BigInteger.valueOf(1024); 463 final BigInteger MB1 = KB1.multiply(KB1); 464 final BigInteger GB1 = MB1.multiply(KB1); 465 final BigInteger GB2 = GB1.add(GB1); 466 final BigInteger TB1 = GB1.multiply(KB1); 467 final BigInteger PB1 = TB1.multiply(KB1); 468 final BigInteger EB1 = PB1.multiply(KB1); 469 assertEquals("0 bytes", FileUtils.byteCountToDisplaySize(BigInteger.ZERO)); 470 assertEquals("1 bytes", FileUtils.byteCountToDisplaySize(BigInteger.ONE)); 471 assertEquals("1023 bytes", FileUtils.byteCountToDisplaySize(b1023)); 472 assertEquals("1 KB", FileUtils.byteCountToDisplaySize(KB1)); 473 assertEquals("1 KB", FileUtils.byteCountToDisplaySize(b1025)); 474 assertEquals("1023 KB", FileUtils.byteCountToDisplaySize(MB1.subtract(BigInteger.ONE))); 475 assertEquals("1 MB", FileUtils.byteCountToDisplaySize(MB1)); 476 assertEquals("1 MB", FileUtils.byteCountToDisplaySize(MB1.add(BigInteger.ONE))); 477 assertEquals("1023 MB", FileUtils.byteCountToDisplaySize(GB1.subtract(BigInteger.ONE))); 478 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(GB1)); 479 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(GB1.add(BigInteger.ONE))); 480 assertEquals("2 GB", FileUtils.byteCountToDisplaySize(GB2)); 481 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(GB2.subtract(BigInteger.ONE))); 482 assertEquals("1 TB", FileUtils.byteCountToDisplaySize(TB1)); 483 assertEquals("1 PB", FileUtils.byteCountToDisplaySize(PB1)); 484 assertEquals("1 EB", FileUtils.byteCountToDisplaySize(EB1)); 485 assertEquals("7 EB", FileUtils.byteCountToDisplaySize(Long.MAX_VALUE)); 486 // Other MAX_VALUEs 487 assertEquals("63 KB", FileUtils.byteCountToDisplaySize(BigInteger.valueOf(Character.MAX_VALUE))); 488 assertEquals("31 KB", FileUtils.byteCountToDisplaySize(BigInteger.valueOf(Short.MAX_VALUE))); 489 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(BigInteger.valueOf(Integer.MAX_VALUE))); 490 } 491 492 @SuppressWarnings("NumericOverflow") 493 @Test 494 public void testByteCountToDisplaySizeLong() { 495 assertEquals("0 bytes", FileUtils.byteCountToDisplaySize(0)); 496 assertEquals("1 bytes", FileUtils.byteCountToDisplaySize(1)); 497 assertEquals("1023 bytes", FileUtils.byteCountToDisplaySize(1023)); 498 assertEquals("1 KB", FileUtils.byteCountToDisplaySize(1024)); 499 assertEquals("1 KB", FileUtils.byteCountToDisplaySize(1025)); 500 assertEquals("1023 KB", FileUtils.byteCountToDisplaySize(1024 * 1023)); 501 assertEquals("1 MB", FileUtils.byteCountToDisplaySize(1024 * 1024)); 502 assertEquals("1 MB", FileUtils.byteCountToDisplaySize(1024 * 1025)); 503 assertEquals("1023 MB", FileUtils.byteCountToDisplaySize(1024 * 1024 * 1023)); 504 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(1024 * 1024 * 1024)); 505 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(1024 * 1024 * 1025)); 506 assertEquals("2 GB", FileUtils.byteCountToDisplaySize(1024L * 1024 * 1024 * 2)); 507 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(1024 * 1024 * 1024 * 2 - 1)); 508 assertEquals("1 TB", FileUtils.byteCountToDisplaySize(1024L * 1024 * 1024 * 1024)); 509 assertEquals("1 PB", FileUtils.byteCountToDisplaySize(1024L * 1024 * 1024 * 1024 * 1024)); 510 assertEquals("1 EB", FileUtils.byteCountToDisplaySize(1024L * 1024 * 1024 * 1024 * 1024 * 1024)); 511 assertEquals("7 EB", FileUtils.byteCountToDisplaySize(Long.MAX_VALUE)); 512 // Other MAX_VALUEs 513 assertEquals("63 KB", FileUtils.byteCountToDisplaySize(Character.MAX_VALUE)); 514 assertEquals("31 KB", FileUtils.byteCountToDisplaySize(Short.MAX_VALUE)); 515 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(Integer.MAX_VALUE)); 516 } 517 518 @Test 519 public void testByteCountToDisplaySizeNumber() { 520 assertEquals("0 bytes", FileUtils.byteCountToDisplaySize(Integer.valueOf(0))); 521 assertEquals("1 bytes", FileUtils.byteCountToDisplaySize(Integer.valueOf(1))); 522 assertEquals("1023 bytes", FileUtils.byteCountToDisplaySize(Integer.valueOf(1023))); 523 assertEquals("1 KB", FileUtils.byteCountToDisplaySize(Integer.valueOf(1024))); 524 assertEquals("1 KB", FileUtils.byteCountToDisplaySize(Integer.valueOf(1025))); 525 assertEquals("1023 KB", FileUtils.byteCountToDisplaySize(Long.valueOf(1024 * 1023))); 526 assertEquals("1 MB", FileUtils.byteCountToDisplaySize(Long.valueOf(1024 * 1024))); 527 assertEquals("1 MB", FileUtils.byteCountToDisplaySize(Long.valueOf(1024 * 1025))); 528 assertEquals("1023 MB", FileUtils.byteCountToDisplaySize(Long.valueOf(1024 * 1024 * 1023))); 529 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(Long.valueOf(1024 * 1024 * 1024))); 530 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(Long.valueOf(1024 * 1024 * 1025))); 531 assertEquals("2 GB", FileUtils.byteCountToDisplaySize(Long.valueOf(1024L * 1024 * 1024 * 2))); 532 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(Long.valueOf(1024 * 1024 * 1024 * 2 - 1))); 533 assertEquals("1 TB", FileUtils.byteCountToDisplaySize(Long.valueOf(1024L * 1024 * 1024 * 1024))); 534 assertEquals("1 PB", FileUtils.byteCountToDisplaySize(Long.valueOf(1024L * 1024 * 1024 * 1024 * 1024))); 535 assertEquals("1 EB", FileUtils.byteCountToDisplaySize(Long.valueOf(1024L * 1024 * 1024 * 1024 * 1024 * 1024))); 536 assertEquals("7 EB", FileUtils.byteCountToDisplaySize(Long.valueOf(Long.MAX_VALUE))); 537 // Other MAX_VALUEs 538 assertEquals("63 KB", FileUtils.byteCountToDisplaySize(Integer.valueOf(Character.MAX_VALUE))); 539 assertEquals("31 KB", FileUtils.byteCountToDisplaySize(Short.valueOf(Short.MAX_VALUE))); 540 assertEquals("1 GB", FileUtils.byteCountToDisplaySize(Integer.valueOf(Integer.MAX_VALUE))); 541 } 542 543 @Test 544 public void testChecksum() throws Exception { 545 // create a test file 546 final String text = "Imagination is more important than knowledge - Einstein"; 547 final File file = new File(tempDirFile, "checksum-test.txt"); 548 FileUtils.writeStringToFile(file, text, "US-ASCII"); 549 550 // compute the expected checksum 551 final Checksum expectedChecksum = new CRC32(); 552 expectedChecksum.update(text.getBytes(StandardCharsets.US_ASCII), 0, text.length()); 553 final long expectedValue = expectedChecksum.getValue(); 554 555 // compute the checksum of the file 556 final Checksum testChecksum = new CRC32(); 557 final Checksum resultChecksum = FileUtils.checksum(file, testChecksum); 558 final long resultValue = resultChecksum.getValue(); 559 560 assertSame(testChecksum, resultChecksum); 561 assertEquals(expectedValue, resultValue); 562 } 563 564 @Test 565 public void testChecksumCRC32() throws Exception { 566 // create a test file 567 final String text = "Imagination is more important than knowledge - Einstein"; 568 final File file = new File(tempDirFile, "checksum-test.txt"); 569 FileUtils.writeStringToFile(file, text, "US-ASCII"); 570 571 // compute the expected checksum 572 final Checksum expectedChecksum = new CRC32(); 573 expectedChecksum.update(text.getBytes(StandardCharsets.US_ASCII), 0, text.length()); 574 final long expectedValue = expectedChecksum.getValue(); 575 576 // compute the checksum of the file 577 final long resultValue = FileUtils.checksumCRC32(file); 578 579 assertEquals(expectedValue, resultValue); 580 } 581 582 @Test 583 public void testChecksumDouble() throws Exception { 584 // create a test file 585 final String text1 = "Imagination is more important than knowledge - Einstein"; 586 final File file1 = new File(tempDirFile, "checksum-test.txt"); 587 FileUtils.writeStringToFile(file1, text1, "US-ASCII"); 588 589 // create a second test file 590 final String text2 = "To be or not to be - Shakespeare"; 591 final File file2 = new File(tempDirFile, "checksum-test2.txt"); 592 FileUtils.writeStringToFile(file2, text2, "US-ASCII"); 593 594 // compute the expected checksum 595 final Checksum expectedChecksum = new CRC32(); 596 expectedChecksum.update(text1.getBytes(StandardCharsets.US_ASCII), 0, text1.length()); 597 expectedChecksum.update(text2.getBytes(StandardCharsets.US_ASCII), 0, text2.length()); 598 final long expectedValue = expectedChecksum.getValue(); 599 600 // compute the checksum of the file 601 final Checksum testChecksum = new CRC32(); 602 FileUtils.checksum(file1, testChecksum); 603 FileUtils.checksum(file2, testChecksum); 604 final long resultValue = testChecksum.getValue(); 605 606 assertEquals(expectedValue, resultValue); 607 } 608 609 @Test 610 public void testChecksumOnDirectory() { 611 assertThrows(IllegalArgumentException.class, () -> FileUtils.checksum(FileUtils.current(), new CRC32())); 612 } 613 614 @Test 615 public void testChecksumOnNullChecksum() throws Exception { 616 // create a test file 617 final String text = "Imagination is more important than knowledge - Einstein"; 618 final File file = new File(tempDirFile, "checksum-test.txt"); 619 FileUtils.writeStringToFile(file, text, "US-ASCII"); 620 assertThrows(NullPointerException.class, () -> FileUtils.checksum(file, null)); 621 } 622 623 @Test 624 public void testChecksumOnNullFile() { 625 assertThrows(NullPointerException.class, () -> FileUtils.checksum(null, new CRC32())); 626 } 627 628 // Compare sizes of a directory tree using long and BigInteger methods 629 @Test 630 public void testCompareSizeOf() { 631 final File start = new File("src/test/java"); 632 final long sizeLong1 = FileUtils.sizeOf(start); 633 final BigInteger sizeBig = FileUtils.sizeOfAsBigInteger(start); 634 final long sizeLong2 = FileUtils.sizeOf(start); 635 assertEquals(sizeLong1, sizeLong2, "Size should not change"); 636 assertEquals(sizeLong1, sizeBig.longValue(), "longSize should equal BigSize"); 637 } 638 639 @Test 640 public void testContentEquals() throws Exception { 641 // Non-existent files 642 final File file = new File(tempDirFile, getName()); 643 final File file2 = new File(tempDirFile, getName() + "2"); 644 assertTrue(FileUtils.contentEquals(null, null)); 645 assertFalse(FileUtils.contentEquals(null, file)); 646 assertFalse(FileUtils.contentEquals(file, null)); 647 // both don't exist 648 assertTrue(FileUtils.contentEquals(file, file)); 649 assertTrue(FileUtils.contentEquals(file, file2)); 650 assertTrue(FileUtils.contentEquals(file2, file2)); 651 assertTrue(FileUtils.contentEquals(file2, file)); 652 653 // Directories 654 assertThrows(IllegalArgumentException.class, () -> FileUtils.contentEquals(tempDirFile, tempDirFile)); 655 656 // Different files 657 final File objFile1 = 658 new File(tempDirFile, getName() + ".object"); 659 FileUtils.copyURLToFile( 660 getClass().getResource("/java/lang/Object.class"), 661 objFile1); 662 663 final File objFile1b = 664 new File(tempDirFile, getName() + ".object2"); 665 FileUtils.copyURLToFile( 666 getClass().getResource("/java/lang/Object.class"), 667 objFile1b); 668 669 final File objFile2 = 670 new File(tempDirFile, getName() + ".collection"); 671 FileUtils.copyURLToFile( 672 getClass().getResource("/java/util/Collection.class"), 673 objFile2); 674 675 assertFalse(FileUtils.contentEquals(objFile1, objFile2)); 676 assertFalse(FileUtils.contentEquals(objFile1b, objFile2)); 677 assertTrue(FileUtils.contentEquals(objFile1, objFile1b)); 678 679 assertTrue(FileUtils.contentEquals(objFile1, objFile1)); 680 assertTrue(FileUtils.contentEquals(objFile1b, objFile1b)); 681 assertTrue(FileUtils.contentEquals(objFile2, objFile2)); 682 683 // Equal files 684 file.createNewFile(); 685 file2.createNewFile(); 686 assertTrue(FileUtils.contentEquals(file, file)); 687 assertTrue(FileUtils.contentEquals(file, file2)); 688 } 689 690 @Test 691 public void testContentEqualsIgnoreEOL() throws Exception { 692 // Non-existent files 693 final File file1 = new File(tempDirFile, getName()); 694 final File file2 = new File(tempDirFile, getName() + "2"); 695 assertTrue(FileUtils.contentEqualsIgnoreEOL(null, null, null)); 696 assertFalse(FileUtils.contentEqualsIgnoreEOL(null, file1, null)); 697 assertFalse(FileUtils.contentEqualsIgnoreEOL(file1, null, null)); 698 // both don't exist 699 assertTrue(FileUtils.contentEqualsIgnoreEOL(file1, file1, null)); 700 assertTrue(FileUtils.contentEqualsIgnoreEOL(file1, file2, null)); 701 assertTrue(FileUtils.contentEqualsIgnoreEOL(file2, file2, null)); 702 assertTrue(FileUtils.contentEqualsIgnoreEOL(file2, file1, null)); 703 704 // Directories 705 assertThrows(IllegalArgumentException.class, 706 () -> FileUtils.contentEqualsIgnoreEOL(tempDirFile, tempDirFile, null)); 707 708 // Different files 709 final File tfile1 = new File(tempDirFile, getName() + ".txt1"); 710 FileUtils.write(tfile1, "123\r"); 711 712 final File tfile2 = new File(tempDirFile, getName() + ".txt2"); 713 FileUtils.write(tfile2, "123\n"); 714 715 final File tfile3 = new File(tempDirFile, getName() + ".collection"); 716 FileUtils.write(tfile3, "123\r\n2"); 717 718 assertTrue(FileUtils.contentEqualsIgnoreEOL(tfile1, tfile1, null)); 719 assertTrue(FileUtils.contentEqualsIgnoreEOL(tfile2, tfile2, null)); 720 assertTrue(FileUtils.contentEqualsIgnoreEOL(tfile3, tfile3, null)); 721 722 assertTrue(FileUtils.contentEqualsIgnoreEOL(tfile1, tfile2, null)); 723 assertFalse(FileUtils.contentEqualsIgnoreEOL(tfile1, tfile3, null)); 724 assertFalse(FileUtils.contentEqualsIgnoreEOL(tfile2, tfile3, null)); 725 726 final URL urlCR = getClass().getResource("FileUtilsTestDataCR.dat"); 727 assertNotNull(urlCR); 728 final File cr = new File(urlCR.toURI()); 729 assertTrue(cr.exists()); 730 731 final URL urlCRLF = getClass().getResource("FileUtilsTestDataCRLF.dat"); 732 assertNotNull(urlCRLF); 733 final File crlf = new File(urlCRLF.toURI()); 734 assertTrue(crlf.exists()); 735 736 final URL urlLF = getClass().getResource("FileUtilsTestDataLF.dat"); 737 assertNotNull(urlLF); 738 final File lf = new File(urlLF.toURI()); 739 assertTrue(lf.exists()); 740 741 assertTrue(FileUtils.contentEqualsIgnoreEOL(cr, cr, null)); 742 assertTrue(FileUtils.contentEqualsIgnoreEOL(crlf, crlf, null)); 743 assertTrue(FileUtils.contentEqualsIgnoreEOL(lf, lf, null)); 744 745 assertTrue(FileUtils.contentEqualsIgnoreEOL(cr, crlf, null)); 746 assertTrue(FileUtils.contentEqualsIgnoreEOL(cr, lf, null)); 747 assertTrue(FileUtils.contentEqualsIgnoreEOL(crlf, lf, null)); 748 749 // Check the files behave OK when EOL is not ignored 750 assertTrue(FileUtils.contentEquals(cr, cr)); 751 assertTrue(FileUtils.contentEquals(crlf, crlf)); 752 assertTrue(FileUtils.contentEquals(lf, lf)); 753 754 assertFalse(FileUtils.contentEquals(cr, crlf)); 755 assertFalse(FileUtils.contentEquals(cr, lf)); 756 assertFalse(FileUtils.contentEquals(crlf, lf)); 757 758 // Equal files 759 file1.createNewFile(); 760 file2.createNewFile(); 761 assertTrue(FileUtils.contentEqualsIgnoreEOL(file1, file1, null)); 762 assertTrue(FileUtils.contentEqualsIgnoreEOL(file1, file2, null)); 763 } 764 765 @Test 766 public void testCopyDirectoryExceptions() { 767 // 768 // NullPointerException 769 assertThrows(NullPointerException.class, () -> FileUtils.copyDirectory(null, null)); 770 assertThrows(NullPointerException.class, () -> FileUtils.copyDirectory(null, testFile1)); 771 assertThrows(NullPointerException.class, () -> FileUtils.copyDirectory(testFile1, null)); 772 assertThrows(NullPointerException.class, () -> FileUtils.copyDirectory(null, new File("a"))); 773 // 774 // IllegalArgumentException 775 assertThrows(IllegalArgumentException.class, () -> FileUtils.copyDirectory(testFile1, new File("a"))); 776 assertThrows(IllegalArgumentException.class, () -> FileUtils.copyDirectory(testFile1, new File("a"))); 777 assertThrows(IllegalArgumentException.class, () -> FileUtils.copyDirectory(tempDirFile, tempDirFile)); 778 // 779 // IOException 780 assertThrows(IOException.class, () -> FileUtils.copyDirectory(new File("doesnt-exist"), new File("a"))); 781 assertThrows(IllegalArgumentException.class, () -> FileUtils.copyDirectory(tempDirFile, testFile1)); 782 } 783 784 @Test 785 public void testCopyDirectoryFiltered() throws IOException { 786 final File grandParentDir = new File(tempDirFile, "grandparent"); 787 final File parentDir = new File(grandParentDir, "parent"); 788 final File childDir = new File(parentDir, "child"); 789 createFilesForTestCopyDirectory(grandParentDir, parentDir, childDir); 790 791 final NameFileFilter filter = new NameFileFilter("parent", "child", "file3.txt"); 792 final File destDir = new File(tempDirFile, "copydest"); 793 794 FileUtils.copyDirectory(grandParentDir, destDir, filter); 795 final List<File> files = LIST_WALKER.list(destDir); 796 assertEquals(3, files.size()); 797 assertEquals("parent", files.get(0).getName()); 798 assertEquals("child", files.get(1).getName()); 799 assertEquals("file3.txt", files.get(2).getName()); 800 } 801 802 // @Test public void testToURLs2() throws Exception { 803 // File[] files = new File[] { 804 // new File(temporaryFolder, "file1.txt"), 805 // null, 806 // }; 807 // URL[] urls = FileUtils.toURLs(files); 808 // 809 // assertEquals(files.length, urls.length); 810 // assertTrue(urls[0].toExternalForm().startsWith("file:")); 811 // assertTrue(urls[0].toExternalForm().indexOf("file1.txt") > 0); 812 // assertEquals(null, urls[1]); 813 // } 814 // 815 // @Test public void testToURLs3() throws Exception { 816 // File[] files = null; 817 // URL[] urls = FileUtils.toURLs(files); 818 // 819 // assertEquals(0, urls.length); 820 // } 821 822 @Test 823 public void testCopyDirectoryPreserveDates() throws Exception { 824 final File source = new File(tempDirFile, "source"); 825 final File sourceDirectory = new File(source, "directory"); 826 final File sourceFile = new File(sourceDirectory, "hello.txt"); 827 828 // Prepare source data 829 source.mkdirs(); 830 sourceDirectory.mkdir(); 831 FileUtils.writeStringToFile(sourceFile, "HELLO WORLD", "UTF8"); 832 // Set dates in reverse order to avoid overwriting previous values 833 // Also, use full seconds (arguments are in ms) close to today 834 // but still highly unlikely to occur in the real world 835 assertTrue(setLastModifiedMillis(sourceFile, DATE3)); 836 assertTrue(setLastModifiedMillis(sourceDirectory, DATE2)); 837 assertTrue(setLastModifiedMillis(source, DATE1)); 838 839 final File target = new File(tempDirFile, "target"); 840 final File targetDirectory = new File(target, "directory"); 841 final File targetFile = new File(targetDirectory, "hello.txt"); 842 843 // Test with preserveFileDate disabled 844 // On Windows, the last modified time is copied by default. 845 FileUtils.copyDirectory(source, target, false); 846 assertNotEquals(DATE1, getLastModifiedMillis(target)); 847 assertNotEquals(DATE2, getLastModifiedMillis(targetDirectory)); 848 if (!SystemUtils.IS_OS_WINDOWS) { 849 assertNotEquals(DATE3, getLastModifiedMillis(targetFile)); 850 } 851 FileUtils.deleteDirectory(target); 852 853 // Test with preserveFileDate enabled 854 FileUtils.copyDirectory(source, target, true); 855 assertEquals(DATE1, getLastModifiedMillis(target)); 856 assertEquals(DATE2, getLastModifiedMillis(targetDirectory)); 857 assertEquals(DATE3, getLastModifiedMillis(targetFile)); 858 FileUtils.deleteDirectory(target); 859 860 // also if the target directory already exists (IO-190) 861 target.mkdirs(); 862 FileUtils.copyDirectory(source, target, true); 863 assertEquals(DATE1, getLastModifiedMillis(target)); 864 assertEquals(DATE2, getLastModifiedMillis(targetDirectory)); 865 assertEquals(DATE3, getLastModifiedMillis(targetFile)); 866 FileUtils.deleteDirectory(target); 867 868 // also if the target subdirectory already exists (IO-190) 869 targetDirectory.mkdirs(); 870 FileUtils.copyDirectory(source, target, true); 871 assertEquals(DATE1, getLastModifiedMillis(target)); 872 assertEquals(DATE2, getLastModifiedMillis(targetDirectory)); 873 assertEquals(DATE3, getLastModifiedMillis(targetFile)); 874 FileUtils.deleteDirectory(target); 875 } 876 877 /** Tests IO-141 */ 878 @Test 879 public void testCopyDirectoryToChild() throws IOException { 880 final File grandParentDir = new File(tempDirFile, "grandparent"); 881 final File parentDir = new File(grandParentDir, "parent"); 882 final File childDir = new File(parentDir, "child"); 883 createFilesForTestCopyDirectory(grandParentDir, parentDir, childDir); 884 885 final long expectedCount = LIST_WALKER.list(grandParentDir).size() + LIST_WALKER.list(parentDir).size(); 886 final long expectedSize = FileUtils.sizeOfDirectory(grandParentDir) + FileUtils.sizeOfDirectory(parentDir); 887 FileUtils.copyDirectory(parentDir, childDir); 888 assertEquals(expectedCount, LIST_WALKER.list(grandParentDir).size()); 889 assertEquals(expectedSize, FileUtils.sizeOfDirectory(grandParentDir)); 890 assertTrue(expectedCount > 0, "Count > 0"); 891 assertTrue(expectedSize > 0, "Size > 0"); 892 } 893 894 @Test 895 public void testCopyDirectoryToDirectory_NonExistingDest() throws Exception { 896 if (!testFile1.getParentFile().exists()) { 897 fail("Cannot create file " + testFile1 898 + " as the parent directory does not exist"); 899 } 900 try (final OutputStream output1 = new BufferedOutputStream(Files.newOutputStream(testFile1.toPath()))) { 901 TestUtils.generateTestData(output1, 1234); 902 } 903 if (!testFile2.getParentFile().exists()) { 904 fail("Cannot create file " + testFile2 905 + " as the parent directory does not exist"); 906 } 907 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(testFile2.toPath()))) { 908 TestUtils.generateTestData(output, 4321); 909 } 910 final File srcDir = tempDirFile; 911 final File subDir = new File(srcDir, "sub"); 912 subDir.mkdir(); 913 final File subFile = new File(subDir, "A.txt"); 914 FileUtils.writeStringToFile(subFile, "HELLO WORLD", "UTF8"); 915 final File destDir = new File(FileUtils.getTempDirectoryPath(), "tmp-FileUtilsTestCase"); 916 FileUtils.deleteDirectory(destDir); 917 final File actualDestDir = new File(destDir, srcDir.getName()); 918 919 FileUtils.copyDirectoryToDirectory(srcDir, destDir); 920 921 assertTrue(destDir.exists(), "Check exists"); 922 assertTrue(actualDestDir.exists(), "Check exists"); 923 final long srcSize = FileUtils.sizeOfDirectory(srcDir); 924 assertTrue(srcSize > 0, "Size > 0"); 925 assertEquals(srcSize, FileUtils.sizeOfDirectory(actualDestDir), "Check size"); 926 assertTrue(new File(actualDestDir, "sub/A.txt").exists()); 927 FileUtils.deleteDirectory(destDir); 928 } 929 930 @Test 931 public void testCopyDirectoryToExistingDest() throws Exception { 932 if (!testFile1.getParentFile().exists()) { 933 fail("Cannot create file " + testFile1 934 + " as the parent directory does not exist"); 935 } 936 try (final OutputStream output1 = new BufferedOutputStream(Files.newOutputStream(testFile1.toPath()))) { 937 TestUtils.generateTestData(output1, 1234); 938 } 939 if (!testFile2.getParentFile().exists()) { 940 fail("Cannot create file " + testFile2 941 + " as the parent directory does not exist"); 942 } 943 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(testFile2.toPath()))) { 944 TestUtils.generateTestData(output, 4321); 945 } 946 final File srcDir = tempDirFile; 947 final File subDir = new File(srcDir, "sub"); 948 subDir.mkdir(); 949 final File subFile = new File(subDir, "A.txt"); 950 FileUtils.writeStringToFile(subFile, "HELLO WORLD", "UTF8"); 951 final File destDir = new File(System.getProperty("java.io.tmpdir"), "tmp-FileUtilsTestCase"); 952 FileUtils.deleteDirectory(destDir); 953 destDir.mkdirs(); 954 955 FileUtils.copyDirectory(srcDir, destDir); 956 957 final long srcSize = FileUtils.sizeOfDirectory(srcDir); 958 assertTrue(srcSize > 0, "Size > 0"); 959 assertEquals(srcSize, FileUtils.sizeOfDirectory(destDir)); 960 assertTrue(new File(destDir, "sub/A.txt").exists()); 961 } 962 963 /** Test IO-141 */ 964 @Test 965 public void testCopyDirectoryToGrandChild() throws IOException { 966 final File grandParentDir = new File(tempDirFile, "grandparent"); 967 final File parentDir = new File(grandParentDir, "parent"); 968 final File childDir = new File(parentDir, "child"); 969 createFilesForTestCopyDirectory(grandParentDir, parentDir, childDir); 970 971 final long expectedCount = LIST_WALKER.list(grandParentDir).size() * 2; 972 final long expectedSize = FileUtils.sizeOfDirectory(grandParentDir) * 2; 973 FileUtils.copyDirectory(grandParentDir, childDir); 974 assertEquals(expectedCount, LIST_WALKER.list(grandParentDir).size()); 975 assertEquals(expectedSize, FileUtils.sizeOfDirectory(grandParentDir)); 976 assertTrue(expectedSize > 0, "Size > 0"); 977 } 978 979 /** Tests IO-217 FileUtils.copyDirectoryToDirectory makes infinite loops */ 980 @Test 981 public void testCopyDirectoryToItself() throws Exception { 982 final File dir = new File(tempDirFile, "itself"); 983 dir.mkdirs(); 984 FileUtils.copyDirectoryToDirectory(dir, dir); 985 assertEquals(1, LIST_WALKER.list(dir).size()); 986 } 987 988 @Test 989 public void testCopyDirectoryToNonExistingDest() throws Exception { 990 if (!testFile1.getParentFile().exists()) { 991 fail("Cannot create file " + testFile1 992 + " as the parent directory does not exist"); 993 } 994 try (final OutputStream output1 = new BufferedOutputStream(Files.newOutputStream(testFile1.toPath()))) { 995 TestUtils.generateTestData(output1, 1234); 996 } 997 if (!testFile2.getParentFile().exists()) { 998 fail("Cannot create file " + testFile2 999 + " as the parent directory does not exist"); 1000 } 1001 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(testFile2.toPath()));) { 1002 TestUtils.generateTestData(output, 4321); 1003 } 1004 final File srcDir = tempDirFile; 1005 final File subDir = new File(srcDir, "sub"); 1006 subDir.mkdir(); 1007 final File subFile = new File(subDir, "A.txt"); 1008 FileUtils.writeStringToFile(subFile, "HELLO WORLD", "UTF8"); 1009 final File destDir = new File(FileUtils.getTempDirectoryPath(), "tmp-FileUtilsTestCase"); 1010 FileUtils.deleteDirectory(destDir); 1011 1012 FileUtils.copyDirectory(srcDir, destDir); 1013 1014 assertTrue(destDir.exists(), "Check exists"); 1015 final long sizeOfSrcDirectory = FileUtils.sizeOfDirectory(srcDir); 1016 assertTrue(sizeOfSrcDirectory > 0, "Size > 0"); 1017 assertEquals(sizeOfSrcDirectory, FileUtils.sizeOfDirectory(destDir), "Check size"); 1018 assertTrue(new File(destDir, "sub/A.txt").exists()); 1019 FileUtils.deleteDirectory(destDir); 1020 } 1021 1022 /** 1023 * Test for https://github.com/apache/commons-io/pull/371. The dir name 'par' is a substring of 1024 * the dir name 'parent' which is the parent of the 'parent/child' dir. 1025 */ 1026 @Test 1027 public void testCopyDirectoryWithPotentialFalsePartialMatch() throws IOException { 1028 final File grandParentDir = new File(tempDirFile, "grandparent"); 1029 final File parentDir = new File(grandParentDir, "parent"); 1030 final File parDir = new File(grandParentDir, "par"); 1031 final File childDir = new File(parentDir, "child"); 1032 createFilesForTestCopyDirectory(grandParentDir, parDir, childDir); 1033 1034 final List<File> initFiles = LIST_WALKER.list(grandParentDir); 1035 final List<File> parFiles = LIST_WALKER.list(parDir); 1036 final long expectedCount = initFiles.size() + parFiles.size(); 1037 final long expectedSize = FileUtils.sizeOfDirectory(grandParentDir) + FileUtils.sizeOfDirectory(parDir); 1038 FileUtils.copyDirectory(parDir, childDir); 1039 final List<File> latestFiles = LIST_WALKER.list(grandParentDir); 1040 assertEquals(expectedCount, latestFiles.size()); 1041 assertEquals(expectedSize, FileUtils.sizeOfDirectory(grandParentDir)); 1042 assertTrue(expectedCount > 0, "Count > 0"); 1043 assertTrue(expectedSize > 0, "Size > 0"); 1044 final Set<String> initFilePaths = getFilePathSet(initFiles); 1045 final Set<String> newFilePaths = getFilePathSet(latestFiles); 1046 newFilePaths.removeAll(initFilePaths); 1047 assertEquals(parFiles.size(), newFilePaths.size()); 1048 } 1049 1050 @Test 1051 public void testCopyFile1() throws Exception { 1052 final File destination = new File(tempDirFile, "copy1.txt"); 1053 1054 backDateFile10Minutes(testFile1); // set test file back 10 minutes 1055 1056 FileUtils.copyFile(testFile1, destination); 1057 assertTrue(destination.exists(), "Check Exist"); 1058 assertEquals(testFile1Size, destination.length(), "Check Full copy"); 1059 assertEquals(getLastModifiedMillis(testFile1), getLastModifiedMillis(destination), "Check last modified date preserved"); 1060 } 1061 1062 @Test 1063 public void testCopyFile1ToDir() throws Exception { 1064 final File directory = new File(tempDirFile, "subdir"); 1065 if (!directory.exists()) { 1066 directory.mkdirs(); 1067 } 1068 final File destination = new File(directory, testFile1.getName()); 1069 1070 backDateFile10Minutes(testFile1); 1071 1072 FileUtils.copyFileToDirectory(testFile1, directory); 1073 assertTrue(destination.exists(), "Check Exist"); 1074 assertEquals(testFile1Size, destination.length(), "Check Full copy"); 1075 assertEquals(FileUtils.lastModified(testFile1), FileUtils.lastModified(destination), "Check last modified date preserved"); 1076 1077 assertThrows(IllegalArgumentException.class, () -> FileUtils.copyFileToDirectory(destination, directory), 1078 "Should not be able to copy a file into the same directory as itself"); 1079 } 1080 1081 @Test 1082 public void testCopyFile2() throws Exception { 1083 final File destination = new File(tempDirFile, "copy2.txt"); 1084 1085 backDateFile10Minutes(testFile1); // set test file back 10 minutes 1086 1087 FileUtils.copyFile(testFile1, destination); 1088 assertTrue(destination.exists(), "Check Exist"); 1089 assertEquals(testFile2Size, destination.length(), "Check Full copy"); 1090 assertEquals(getLastModifiedMillis(testFile1) , getLastModifiedMillis(destination), "Check last modified date preserved"); 1091 } 1092 1093 @Test 1094 public void testCopyFile2ToDir() throws Exception { 1095 final File directory = new File(tempDirFile, "subdir"); 1096 if (!directory.exists()) { 1097 directory.mkdirs(); 1098 } 1099 final File destination = new File(directory, testFile1.getName()); 1100 1101 backDateFile10Minutes(testFile1); 1102 1103 FileUtils.copyFileToDirectory(testFile1, directory); 1104 assertTrue(destination.exists(), "Check Exist"); 1105 assertEquals(testFile2Size, destination.length(), "Check Full copy"); 1106 assertEquals(FileUtils.lastModified(testFile1), FileUtils.lastModified(destination), "Check last modified date preserved"); 1107 } 1108 1109 @Test 1110 public void testCopyFile2WithoutFileDatePreservation() throws Exception { 1111 final File destFile = new File(tempDirFile, "copy2.txt"); 1112 1113 backDateFile10Minutes(testFile1); // set test file back 10 minutes 1114 1115 // destination file time should not be less than this (allowing for granularity) 1116 final long nowMillis = System.currentTimeMillis() - 1000L; 1117 // On Windows, the last modified time is copied by default. 1118 FileUtils.copyFile(testFile1, destFile, false); 1119 assertTrue(destFile.exists(), "Check Exist"); 1120 assertEquals(testFile1Size, destFile.length(), "Check Full copy"); 1121 final long destLastModMillis = getLastModifiedMillis(destFile); 1122 final long unexpectedMillis = getLastModifiedMillis(testFile1); 1123 if (!SystemUtils.IS_OS_WINDOWS) { 1124 final long deltaMillis = destLastModMillis - unexpectedMillis; 1125 assertNotEquals(unexpectedMillis, destLastModMillis, 1126 "Check last modified date not same as input, delta " + deltaMillis); 1127 assertTrue(destLastModMillis > nowMillis, 1128 destLastModMillis + " > " + nowMillis + " (delta " + deltaMillis + ")"); 1129 } 1130 } 1131 1132 @Test 1133 @Disabled 1134 public void testCopyFileLarge() throws Exception { 1135 1136 final File largeFile = new File(tempDirFile, "large.txt"); 1137 final File destination = new File(tempDirFile, "copylarge.txt"); 1138 1139 System.out.println("START: " + new java.util.Date()); 1140 if (!largeFile.getParentFile().exists()) { 1141 fail("Cannot create file " + largeFile 1142 + " as the parent directory does not exist"); 1143 } 1144 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(largeFile.toPath()))) { 1145 TestUtils.generateTestData(output, FileUtils.ONE_GB); 1146 } 1147 System.out.println("CREATED: " + new java.util.Date()); 1148 FileUtils.copyFile(largeFile, destination); 1149 System.out.println("COPIED: " + new java.util.Date()); 1150 1151 assertTrue(destination.exists(), "Check Exist"); 1152 assertEquals(largeFile.length(), destination.length(), "Check Full copy"); 1153 } 1154 1155 @Test 1156 public void testCopyFileToOutputStream() throws Exception { 1157 final ByteArrayOutputStream destination = new ByteArrayOutputStream(); 1158 FileUtils.copyFile(testFile1, destination); 1159 assertEquals(testFile1Size, destination.size(), "Check Full copy size"); 1160 final byte[] expected = FileUtils.readFileToByteArray(testFile1); 1161 assertArrayEquals(expected, destination.toByteArray(), "Check Full copy"); 1162 } 1163 1164 @Test 1165 public void testCopyToDirectoryWithDirectory() throws IOException { 1166 final File destDirectory = new File(tempDirFile, "destination"); 1167 if (!destDirectory.exists()) { 1168 destDirectory.mkdirs(); 1169 } 1170 1171 // Create a test directory 1172 final File inputDirectory = new File(tempDirFile, "input"); 1173 if (!inputDirectory.exists()) { 1174 inputDirectory.mkdirs(); 1175 } 1176 final File outputDirDestination = new File(destDirectory, inputDirectory.getName()); 1177 FileUtils.copyToDirectory(testFile1, inputDirectory); 1178 final File destFile1 = new File(outputDirDestination, testFile1.getName()); 1179 FileUtils.copyToDirectory(testFile2, inputDirectory); 1180 final File destFile2 = new File(outputDirDestination, testFile2.getName()); 1181 1182 FileUtils.copyToDirectory(inputDirectory, destDirectory); 1183 1184 // Check the directory was created 1185 assertTrue(outputDirDestination.exists(), "Check Exists"); 1186 assertTrue(outputDirDestination.isDirectory(), "Check Directory"); 1187 1188 // Check each file 1189 assertTrue(destFile1.exists(), "Check Exists"); 1190 assertEquals(testFile1Size, destFile1.length(), "Check Full Copy"); 1191 assertTrue(destFile2.exists(), "Check Exists"); 1192 assertEquals(testFile2Size, destFile2.length(), "Check Full Copy"); 1193 } 1194 1195 @Test 1196 public void testCopyToDirectoryWithFile() throws IOException { 1197 final File directory = new File(tempDirFile, "subdir"); 1198 if (!directory.exists()) { 1199 directory.mkdirs(); 1200 } 1201 final File destination = new File(directory, testFile1.getName()); 1202 1203 FileUtils.copyToDirectory(testFile1, directory); 1204 assertTrue(destination.exists(), "Check Exists"); 1205 assertEquals(testFile1Size, destination.length(), "Check Full Copy"); 1206 } 1207 1208 @Test 1209 public void testCopyToDirectoryWithFileSourceDoesNotExist() { 1210 assertThrows(IOException.class, 1211 () -> FileUtils.copyToDirectory(new File(tempDirFile, "doesNotExists"), tempDirFile)); 1212 } 1213 1214 @Test 1215 public void testCopyToDirectoryWithFileSourceIsNull() { 1216 assertThrows(NullPointerException.class, () -> FileUtils.copyToDirectory((File) null, tempDirFile)); 1217 } 1218 1219 @Test 1220 public void testCopyToDirectoryWithIterable() throws IOException { 1221 final File directory = new File(tempDirFile, "subdir"); 1222 if (!directory.exists()) { 1223 directory.mkdirs(); 1224 } 1225 1226 final List<File> input = new ArrayList<>(); 1227 input.add(testFile1); 1228 input.add(testFile2); 1229 1230 final File destFile1 = new File(directory, testFile1.getName()); 1231 final File destFile2 = new File(directory, testFile2.getName()); 1232 1233 FileUtils.copyToDirectory(input, directory); 1234 // Check each file 1235 assertTrue(destFile1.exists(), "Check Exists"); 1236 assertEquals(testFile1Size, destFile1.length(), "Check Full Copy"); 1237 assertTrue(destFile2.exists(), "Check Exists"); 1238 assertEquals(testFile2Size, destFile2.length(), "Check Full Copy"); 1239 } 1240 1241 @Test 1242 public void testCopyToDirectoryWithIterableSourceDoesNotExist() { 1243 assertThrows(IOException.class, 1244 () -> FileUtils.copyToDirectory(Collections.singleton(new File(tempDirFile, "doesNotExists")), 1245 tempDirFile)); 1246 } 1247 1248 @Test 1249 public void testCopyToDirectoryWithIterableSourceIsNull() { 1250 assertThrows(NullPointerException.class, () -> FileUtils.copyToDirectory((List<File>) null, tempDirFile)); 1251 } 1252 1253 @Test 1254 public void testCopyToSelf() throws Exception { 1255 final File destination = new File(tempDirFile, "copy3.txt"); 1256 //Prepare a test file 1257 FileUtils.copyFile(testFile1, destination); 1258 assertThrows(IllegalArgumentException.class, () -> FileUtils.copyFile(destination, destination)); 1259 } 1260 1261 @Test 1262 public void testCopyURLToFile() throws Exception { 1263 // Creates file 1264 final File file = new File(tempDirFile, getName()); 1265 assertContentMatchesAfterCopyURLToFileFor("/java/lang/Object.class", file); 1266 //TODO Maybe test copy to itself like for copyFile() 1267 } 1268 1269 @Test 1270 public void testCopyURLToFileCreatesParentDirs() throws Exception { 1271 final File file = managedTempDirPath.resolve("subdir").resolve(getName()).toFile(); 1272 assertContentMatchesAfterCopyURLToFileFor("/java/lang/Object.class", file); 1273 } 1274 1275 @Test 1276 public void testCopyURLToFileReplacesExisting() throws Exception { 1277 final File file = new File(tempDirFile, getName()); 1278 assertContentMatchesAfterCopyURLToFileFor("/java/lang/Object.class", file); 1279 assertContentMatchesAfterCopyURLToFileFor("/java/lang/String.class", file); 1280 } 1281 1282 @Test 1283 public void testCopyURLToFileWithTimeout() throws Exception { 1284 // Creates file 1285 final File file = new File(tempDirFile, "testCopyURLToFileWithTimeout"); 1286 1287 // Loads resource 1288 final String resourceName = "/java/lang/Object.class"; 1289 FileUtils.copyURLToFile(getClass().getResource(resourceName), file, 500, 500); 1290 1291 // Tests that resource was copied correctly 1292 try (InputStream fis = Files.newInputStream(file.toPath()); 1293 InputStream resStream = getClass().getResourceAsStream(resourceName);) { 1294 assertTrue(IOUtils.contentEquals(resStream, fis), "Content is not equal."); 1295 } 1296 //TODO Maybe test copy to itself like for copyFile() 1297 } 1298 1299 /** 1300 * Tests a directory with one file of size 0. 1301 */ 1302 @Test 1303 public void testCountFolders1FileSize0() { 1304 assertEquals(0, FileUtils.sizeOfDirectory(Paths.get("src/test/resources/org/apache/commons/io/dirs-1-file-size-0").toFile())); 1305 } 1306 1307 /** 1308 * Tests a directory with one file of size 1. 1309 */ 1310 @Test 1311 public void testCountFolders1FileSize1() { 1312 assertEquals(1, FileUtils.sizeOfDirectory(Paths.get("src/test/resources/org/apache/commons/io/dirs-1-file-size-1").toFile())); 1313 } 1314 1315 /** 1316 * Tests a directory with two subdirectories, each containing one file of size 1. 1317 */ 1318 @Test 1319 public void testCountFolders2FileSize2() { 1320 assertEquals(2, FileUtils.sizeOfDirectory(Paths.get("src/test/resources/org/apache/commons/io/dirs-2-file-size-2").toFile())); 1321 } 1322 1323 /** 1324 * Tests a directory with two subdirectories, each containing one file of size 1. 1325 */ 1326 @Test 1327 public void testCountFolders2FileSize4() { 1328 assertEquals(8, FileUtils.sizeOfDirectory(Paths.get("src/test/resources/org/apache/commons/io/dirs-2-file-size-4").toFile())); 1329 } 1330 1331 @Test 1332 public void testDecodeUrl() { 1333 assertEquals("", FileUtils.decodeUrl("")); 1334 assertEquals("foo", FileUtils.decodeUrl("foo")); 1335 assertEquals("+", FileUtils.decodeUrl("+")); 1336 assertEquals("% ", FileUtils.decodeUrl("%25%20")); 1337 assertEquals("%20", FileUtils.decodeUrl("%2520")); 1338 assertEquals("jar:file:/C:/dir/sub dir/1.0/foo-1.0.jar!/org/Bar.class", FileUtils 1339 .decodeUrl("jar:file:/C:/dir/sub%20dir/1.0/foo-1.0.jar!/org/Bar.class")); 1340 } 1341 1342 @Test 1343 public void testDecodeUrlEncodingUtf8() { 1344 assertEquals("\u00E4\u00F6\u00FC\u00DF", FileUtils.decodeUrl("%C3%A4%C3%B6%C3%BC%C3%9F")); 1345 } 1346 1347 @Test 1348 public void testDecodeUrlLenient() { 1349 assertEquals(" ", FileUtils.decodeUrl(" ")); 1350 assertEquals("\u00E4\u00F6\u00FC\u00DF", FileUtils.decodeUrl("\u00E4\u00F6\u00FC\u00DF")); 1351 assertEquals("%", FileUtils.decodeUrl("%")); 1352 assertEquals("% ", FileUtils.decodeUrl("%%20")); 1353 assertEquals("%2", FileUtils.decodeUrl("%2")); 1354 assertEquals("%2G", FileUtils.decodeUrl("%2G")); 1355 } 1356 1357 @Test 1358 public void testDecodeUrlNullSafe() { 1359 assertNull(FileUtils.decodeUrl(null)); 1360 } 1361 1362 @Test 1363 public void testDelete() throws Exception { 1364 assertEquals(testFile1, FileUtils.delete(testFile1)); 1365 assertThrows(IOException.class, () -> FileUtils.delete(new File("does not exist.nope"))); 1366 } 1367 1368 @Test 1369 public void testDeleteDirectoryWithNonDirectory() { 1370 assertThrows(IllegalArgumentException.class, () -> FileUtils.deleteDirectory(testFile1)); 1371 } 1372 1373 @Test 1374 public void testDeleteQuietlyDir() throws IOException { 1375 final File testDirectory = new File(tempDirFile, "testDeleteQuietlyDir"); 1376 final File testFile = new File(testDirectory, "testDeleteQuietlyFile"); 1377 testDirectory.mkdirs(); 1378 if (!testFile.getParentFile().exists()) { 1379 fail("Cannot create file " + testFile 1380 + " as the parent directory does not exist"); 1381 } 1382 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(testFile.toPath()))) { 1383 TestUtils.generateTestData(output, 0); 1384 } 1385 1386 assertTrue(testDirectory.exists()); 1387 assertTrue(testFile.exists()); 1388 FileUtils.deleteQuietly(testDirectory); 1389 assertFalse(testDirectory.exists(), "Check No Exist"); 1390 assertFalse(testFile.exists(), "Check No Exist"); 1391 } 1392 1393 @Test 1394 public void testDeleteQuietlyFile() throws IOException { 1395 final File testFile = new File(tempDirFile, "testDeleteQuietlyFile"); 1396 if (!testFile.getParentFile().exists()) { 1397 fail("Cannot create file " + testFile 1398 + " as the parent directory does not exist"); 1399 } 1400 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(testFile.toPath()))) { 1401 TestUtils.generateTestData(output, 0); 1402 } 1403 1404 assertTrue(testFile.exists()); 1405 FileUtils.deleteQuietly(testFile); 1406 assertFalse(testFile.exists(), "Check No Exist"); 1407 } 1408 1409 @Test 1410 public void testDeleteQuietlyForNull() { 1411 FileUtils.deleteQuietly(null); 1412 } 1413 1414 @Test 1415 public void testDeleteQuietlyNonExistent() { 1416 final File testFile = new File("testDeleteQuietlyNonExistent"); 1417 assertFalse(testFile.exists()); 1418 FileUtils.deleteQuietly(testFile); 1419 } 1420 1421 /** 1422 * Tests the FileUtils implementation. 1423 */ 1424 @Test 1425 public void testFileUtils() throws Exception { 1426 // Loads file from classpath 1427 final File file1 = new File(tempDirFile, "test.txt"); 1428 final String filename = file1.getAbsolutePath(); 1429 1430 //Create test file on-the-fly (used to be in CVS) 1431 try (OutputStream out = Files.newOutputStream(file1.toPath())) { 1432 out.write("This is a test".getBytes(StandardCharsets.UTF_8)); 1433 } 1434 1435 final File file2 = new File(tempDirFile, "test2.txt"); 1436 1437 FileUtils.writeStringToFile(file2, filename, UTF_8); 1438 assertTrue(file2.exists()); 1439 assertTrue(file2.length() > 0); 1440 1441 final String file2contents = FileUtils.readFileToString(file2, UTF_8); 1442 assertEquals(filename, file2contents, "Second file's contents correct"); 1443 1444 assertTrue(file2.delete()); 1445 1446 final String contents = FileUtils.readFileToString(new File(filename), UTF_8); 1447 assertEquals("This is a test", contents, "FileUtils.fileRead()"); 1448 1449 } 1450 1451 @Test 1452 public void testForceDeleteAFile1() throws Exception { 1453 final File destination = new File(tempDirFile, "copy1.txt"); 1454 destination.createNewFile(); 1455 assertTrue(destination.exists(), "Copy1.txt doesn't exist to delete"); 1456 FileUtils.forceDelete(destination); 1457 assertFalse(destination.exists(), "Check No Exist"); 1458 } 1459 1460 @Test 1461 public void testForceDeleteAFile2() throws Exception { 1462 final File destination = new File(tempDirFile, "copy2.txt"); 1463 destination.createNewFile(); 1464 assertTrue(destination.exists(), "Copy2.txt doesn't exist to delete"); 1465 FileUtils.forceDelete(destination); 1466 assertFalse(destination.exists(), "Check No Exist"); 1467 } 1468 1469 @Test 1470 public void testForceDeleteAFile3() { 1471 final File destination = new File(tempDirFile, "no_such_file"); 1472 assertFalse(destination.exists(), "Check No Exist"); 1473 assertThrows(IOException.class, () -> FileUtils.forceDelete(destination)); 1474 1475 } 1476 1477 @Test 1478 public void testForceDeleteDir() throws Exception { 1479 final File testDirectory = tempDirFile; 1480 assertTrue(testDirectory.exists(), "TestDirectory must exist"); 1481 FileUtils.forceDelete(testDirectory); 1482 assertFalse(testDirectory.exists(), "TestDirectory must not exist"); 1483 } 1484 1485 @Test 1486 public void testForceDeleteReadOnlyFile() throws Exception { 1487 try (TempFile destination = TempFile.create("test-", ".txt")) { 1488 final File file = destination.toFile(); 1489 assertTrue(file.setReadOnly()); 1490 assertTrue(file.canRead()); 1491 assertFalse(file.canWrite()); 1492 // sanity check that File.delete() deletes read-only files. 1493 assertTrue(file.delete()); 1494 } 1495 try (TempFile destination = TempFile.create("test-", ".txt")) { 1496 final File file = destination.toFile(); 1497 // real test 1498 assertTrue(file.setReadOnly()); 1499 assertTrue(file.canRead()); 1500 assertFalse(file.canWrite()); 1501 assertTrue(file.exists(), "File doesn't exist to delete"); 1502 FileUtils.forceDelete(file); 1503 assertFalse(file.exists(), "Check deletion"); 1504 } 1505 } 1506 1507 @Test 1508 public void testForceMkdir() throws Exception { 1509 // Tests with existing directory 1510 FileUtils.forceMkdir(tempDirFile); 1511 1512 // Creates test file 1513 final File testFile = new File(tempDirFile, getName()); 1514 testFile.createNewFile(); 1515 assertTrue(testFile.exists(), "Test file does not exist."); 1516 1517 // Tests with existing file 1518 assertThrows(IOException.class, () -> FileUtils.forceMkdir(testFile)); 1519 1520 testFile.delete(); 1521 1522 // Tests with non-existent directory 1523 FileUtils.forceMkdir(testFile); 1524 assertTrue(testFile.exists(), "Directory was not created."); 1525 1526 // noop 1527 FileUtils.forceMkdir(null); 1528 } 1529 1530 @Test 1531 public void testForceMkdirParent() throws Exception { 1532 // Tests with existing directory 1533 assertTrue(tempDirFile.exists()); 1534 final File testParentDir = new File(tempDirFile, "testForceMkdirParent"); 1535 testParentDir.delete(); 1536 assertFalse(testParentDir.exists()); 1537 final File testFile = new File(testParentDir, "test.txt"); 1538 assertFalse(testParentDir.exists()); 1539 assertFalse(testFile.exists()); 1540 // Create 1541 FileUtils.forceMkdirParent(testFile); 1542 assertTrue(testParentDir.exists()); 1543 assertFalse(testFile.exists()); 1544 // Again 1545 FileUtils.forceMkdirParent(testFile); 1546 assertTrue(testParentDir.exists()); 1547 assertFalse(testFile.exists()); 1548 } 1549 1550 @Test 1551 public void testGetFile() { 1552 final File expected_A = new File("src"); 1553 final File expected_B = new File(expected_A, "main"); 1554 final File expected_C = new File(expected_B, "java"); 1555 assertEquals(expected_A, FileUtils.getFile("src"), "A"); 1556 assertEquals(expected_B, FileUtils.getFile("src", "main"), "B"); 1557 assertEquals(expected_C, FileUtils.getFile("src", "main", "java"), "C"); 1558 assertThrows(NullPointerException.class, () -> FileUtils.getFile((String[]) null)); 1559 1560 } 1561 1562 @Test 1563 public void testGetFile_Parent() { 1564 final File parent = new File("parent"); 1565 final File expected_A = new File(parent, "src"); 1566 final File expected_B = new File(expected_A, "main"); 1567 final File expected_C = new File(expected_B, "java"); 1568 assertEquals(expected_A, FileUtils.getFile(parent, "src"), "A"); 1569 assertEquals(expected_B, FileUtils.getFile(parent, "src", "main"), "B"); 1570 assertEquals(expected_C, FileUtils.getFile(parent, "src", "main", "java"), "C"); 1571 assertThrows(NullPointerException.class, () -> FileUtils.getFile(parent, (String[]) null)); 1572 assertThrows(NullPointerException.class, () -> FileUtils.getFile((File) null, "src")); 1573 } 1574 1575 @Test 1576 public void testGetTempDirectory() { 1577 final File tempDirectory = new File(FileUtils.getTempDirectoryPath()); 1578 assertEquals(tempDirectory, FileUtils.getTempDirectory()); 1579 } 1580 1581 @Test 1582 public void testGetTempDirectoryPath() { 1583 assertEquals(System.getProperty("java.io.tmpdir"), FileUtils.getTempDirectoryPath()); 1584 } 1585 1586 @Test 1587 public void testGetUserDirectory() { 1588 final File userDirectory = new File(System.getProperty("user.home")); 1589 assertEquals(userDirectory, FileUtils.getUserDirectory()); 1590 } 1591 1592 @Test 1593 public void testGetUserDirectoryPath() { 1594 assertEquals(System.getProperty("user.home"), FileUtils.getUserDirectoryPath()); 1595 } 1596 1597 @Test 1598 public void testIO276() throws Exception { 1599 final File dir = new File("target", "IO276"); 1600 assertTrue(dir.mkdirs(), dir + " should not be present"); 1601 final File file = new File(dir, "IO276.txt"); 1602 assertTrue(file.createNewFile(), file + " should not be present"); 1603 FileUtils.forceDeleteOnExit(dir); 1604 // If this does not work, test will fail next time (assuming target is not cleaned) 1605 } 1606 1607 @Test 1608 public void testIO300() { 1609 final File testDirectory = tempDirFile; 1610 final File src = new File(testDirectory, "dir1"); 1611 final File dest = new File(src, "dir2"); 1612 assertTrue(dest.mkdirs()); 1613 assertTrue(src.exists()); 1614 assertThrows(IOException.class, () -> FileUtils.moveDirectoryToDirectory(src, dest, false)); 1615 assertTrue(src.exists()); 1616 } 1617 1618 @Test 1619 public void testIO575() throws IOException { 1620 final Path sourceDir = Files.createTempDirectory("source-dir"); 1621 final String filename = "some-file"; 1622 final Path sourceFile = Files.createFile(sourceDir.resolve(filename)); 1623 1624 assertEquals(SystemUtils.IS_OS_WINDOWS, sourceFile.toFile().canExecute()); 1625 1626 sourceFile.toFile().setExecutable(true); 1627 1628 assertTrue(sourceFile.toFile().canExecute()); 1629 1630 final Path destDir = Files.createTempDirectory("some-empty-destination"); 1631 1632 FileUtils.copyDirectory(sourceDir.toFile(), destDir.toFile()); 1633 1634 final Path destFile = destDir.resolve(filename); 1635 1636 assertTrue(destFile.toFile().exists()); 1637 assertTrue(destFile.toFile().canExecute()); 1638 } 1639 1640 @Test 1641 public void testIsDirectory() throws IOException { 1642 assertFalse(FileUtils.isDirectory(null)); 1643 1644 assertTrue(FileUtils.isDirectory(tempDirFile)); 1645 assertFalse(FileUtils.isDirectory(testFile1)); 1646 1647 final File tempDirAsFile; 1648 try (TempDirectory tempDir = TempDirectory.create(getClass().getCanonicalName())) { 1649 tempDirAsFile = tempDir.toFile(); 1650 assertTrue(FileUtils.isDirectory(tempDirAsFile)); 1651 } 1652 assertFalse(FileUtils.isDirectory(tempDirAsFile)); 1653 } 1654 1655 @Test 1656 public void testIsEmptyDirectory() throws IOException { 1657 try (TempDirectory tempDir = TempDirectory.create(getClass().getCanonicalName())) { 1658 final File tempDirAsFile = tempDir.toFile(); 1659 Assertions.assertTrue(FileUtils.isEmptyDirectory(tempDirAsFile)); 1660 } 1661 Assertions.assertFalse(FileUtils.isEmptyDirectory(PathUtilsIsEmptyTest.DIR_SIZE_1.toFile())); 1662 } 1663 1664 @ParameterizedTest 1665 @ValueSource(longs = {1L, 100L, 1_000L, 10_000L, 100_000L, 1_000_000L}) 1666 public void testIsFileNewerOlder(final long millis) throws Exception { 1667 // Files 1668 final File oldFile = new File(tempDirFile, "FileUtils-old.txt"); 1669 final File refFile = new File(tempDirFile, "FileUtils-reference.txt"); 1670 final File newFile = new File(tempDirFile, "FileUtils-new.txt"); 1671 final File invalidFile = new File(tempDirFile, "FileUtils-invalid-file.txt"); 1672 // Paths 1673 final Path oldPath = oldFile.toPath(); 1674 final Path refPath = refFile.toPath(); 1675 final Path newPath = newFile.toPath(); 1676 // FileTimes 1677 // TODO What is wrong with Java 8 on macOS? Or is this a macOS file system issue? 1678 final long actualMillis = SystemUtils.IS_OS_MAC && SystemUtils.IS_JAVA_1_8 ? millis + 1000 : millis; 1679 final FileTime oldFileTime = FileTime.from(actualMillis * 1, TimeUnit.MILLISECONDS); 1680 final FileTime refFileTime = FileTime.from(actualMillis * 2, TimeUnit.MILLISECONDS); 1681 final FileTime testFileTime = FileTime.from(actualMillis * 3, TimeUnit.MILLISECONDS); 1682 final FileTime newFileTime = FileTime.from(actualMillis * 4, TimeUnit.MILLISECONDS); 1683 1684 // Create fixtures 1685 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(oldPath))) { 1686 TestUtils.generateTestData(output, 0); 1687 } 1688 Files.setLastModifiedTime(oldPath, oldFileTime); 1689 1690 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(refPath))) { 1691 TestUtils.generateTestData(output, 0); 1692 } 1693 Files.setLastModifiedTime(refPath, refFileTime); 1694 1695 final Date date = new Date(testFileTime.toMillis()); 1696 final long now = date.getTime(); 1697 final Instant instant = date.toInstant(); 1698 final ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()); 1699 final OffsetDateTime offsetDateTime = zonedDateTime.toOffsetDateTime(); 1700 final LocalDateTime localDateTime = zonedDateTime.toLocalDateTime(); 1701 final LocalDate localDate = zonedDateTime.toLocalDate(); 1702 final LocalDate localDatePlusDay = localDate.plusDays(1); 1703 final LocalTime localTime0 = LocalTime.MIDNIGHT; 1704 final OffsetTime offsetTime0 = OffsetTime.of(localTime0, ZoneOffset.UTC); 1705 1706 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(newPath))) { 1707 TestUtils.generateTestData(output, 0); 1708 } 1709 Files.setLastModifiedTime(newPath, newFileTime); 1710 1711 // Test 1712 assertFalse(FileUtils.isFileNewer(oldFile, refFile), "Old File - Newer - File"); 1713 assertFalse(FileUtils.isFileNewer(oldFile, date), "Old File - Newer - Date"); 1714 assertFalse(FileUtils.isFileNewer(oldFile, now), "Old File - Newer - Mili"); 1715 assertFalse(FileUtils.isFileNewer(oldFile, instant), "Old File - Newer - Instant"); 1716 assertFalse(FileUtils.isFileNewer(oldFile, zonedDateTime), "Old File - Newer - ZonedDateTime"); 1717 assertFalse(FileUtils.isFileNewer(oldFile, offsetDateTime), "Old File - Newer - OffsetDateTime"); 1718 assertFalse(FileUtils.isFileNewer(oldFile, localDateTime), "Old File - Newer - LocalDateTime"); 1719 assertFalse(FileUtils.isFileNewer(oldFile, localDateTime, ZoneId.systemDefault()), "Old File - Newer - LocalDateTime,ZoneId"); 1720 assertFalse(FileUtils.isFileNewer(oldFile, localDate), "Old File - Newer - LocalDate"); 1721 assertTrue(FileUtils.isFileNewer(oldFile, localDate, localTime0), "Old File - Newer - LocalDate,LocalTime"); 1722 assertTrue(FileUtils.isFileNewer(oldFile, localDate, offsetTime0), "Old File - Newer - LocalDate,OffsetTime"); 1723 assertFalse(FileUtils.isFileNewer(oldFile, localDatePlusDay), "Old File - Newer - LocalDate plus one day"); 1724 assertFalse(FileUtils.isFileNewer(oldFile, localDatePlusDay, localTime0), "Old File - Newer - LocalDate plus one day,LocalTime"); 1725 assertFalse(FileUtils.isFileNewer(oldFile, localDatePlusDay, offsetTime0), "Old File - Newer - LocalDate plus one day,OffsetTime"); 1726 1727 assertTrue(FileUtils.isFileNewer(newFile, refFile), "New File - Newer - File"); 1728 assertTrue(FileUtils.isFileNewer(newFile, date), "New File - Newer - Date"); 1729 assertTrue(FileUtils.isFileNewer(newFile, now), "New File - Newer - Mili"); 1730 assertTrue(FileUtils.isFileNewer(newFile, instant), "New File - Newer - Instant"); 1731 assertTrue(FileUtils.isFileNewer(newFile, zonedDateTime), "New File - Newer - ZonedDateTime"); 1732 assertTrue(FileUtils.isFileNewer(newFile, offsetDateTime), "New File - Newer - OffsetDateTime"); 1733 assertTrue(FileUtils.isFileNewer(newFile, localDateTime), "New File - Newer - LocalDateTime"); 1734 assertTrue(FileUtils.isFileNewer(newFile, localDateTime, ZoneId.systemDefault()), "New File - Newer - LocalDateTime,ZoneId"); 1735 assertFalse(FileUtils.isFileNewer(newFile, localDate), "New File - Newer - LocalDate"); 1736 assertTrue(FileUtils.isFileNewer(newFile, localDate, localTime0), "New File - Newer - LocalDate,LocalTime"); 1737 assertTrue(FileUtils.isFileNewer(newFile, localDate, offsetTime0), "New File - Newer - LocalDate,OffsetTime"); 1738 assertFalse(FileUtils.isFileNewer(newFile, localDatePlusDay), "New File - Newer - LocalDate plus one day"); 1739 assertFalse(FileUtils.isFileNewer(newFile, localDatePlusDay, localTime0), "New File - Newer - LocalDate plus one day,LocalTime"); 1740 assertFalse(FileUtils.isFileNewer(newFile, localDatePlusDay, offsetTime0), "New File - Newer - LocalDate plus one day,OffsetTime"); 1741 assertFalse(FileUtils.isFileNewer(invalidFile, refFile), "Invalid - Newer - File"); 1742 assertThrows(IllegalArgumentException.class, () -> FileUtils.isFileNewer(newFile, invalidFile)); 1743 1744 // Test isFileOlder() 1745 assertTrue(FileUtils.isFileOlder(oldFile, refFile), "Old File - Older - File"); 1746 assertTrue(FileUtils.isFileOlder(oldFile, date), "Old File - Older - Date"); 1747 assertTrue(FileUtils.isFileOlder(oldFile, now), "Old File - Older - Mili"); 1748 assertTrue(FileUtils.isFileOlder(oldFile, instant), "Old File - Older - Instant"); 1749 assertTrue(FileUtils.isFileOlder(oldFile, zonedDateTime), "Old File - Older - ZonedDateTime"); 1750 assertTrue(FileUtils.isFileOlder(oldFile, offsetDateTime), "Old File - Older - OffsetDateTime"); 1751 assertTrue(FileUtils.isFileOlder(oldFile, localDateTime), "Old File - Older - LocalDateTime"); 1752 assertTrue(FileUtils.isFileOlder(oldFile, localDateTime, ZoneId.systemDefault()), "Old File - Older - LocalDateTime,LocalTime"); 1753 assertTrue(FileUtils.isFileOlder(oldFile, localDate), "Old File - Older - LocalDate"); 1754 assertFalse(FileUtils.isFileOlder(oldFile, localDate, localTime0), "Old File - Older - LocalDate,LocalTime"); 1755 assertFalse(FileUtils.isFileOlder(oldFile, localDate, offsetTime0), "Old File - Older - LocalDate,OffsetTime"); 1756 assertTrue(FileUtils.isFileOlder(oldFile, localDatePlusDay), "Old File - Older - LocalDate plus one day"); 1757 assertTrue(FileUtils.isFileOlder(oldFile, localDatePlusDay, localTime0), "Old File - Older - LocalDate plus one day,LocalTime"); 1758 assertTrue(FileUtils.isFileOlder(oldFile, localDatePlusDay, offsetTime0), "Old File - Older - LocalDate plus one day,OffsetTime"); 1759 1760 assertFalse(FileUtils.isFileOlder(newFile, refFile), "New File - Older - File"); 1761 assertFalse(FileUtils.isFileOlder(newFile, date), "New File - Older - Date"); 1762 assertFalse(FileUtils.isFileOlder(newFile, now), "New File - Older - Mili"); 1763 assertFalse(FileUtils.isFileOlder(newFile, instant), "New File - Older - Instant"); 1764 assertFalse(FileUtils.isFileOlder(newFile, zonedDateTime), "New File - Older - ZonedDateTime"); 1765 assertFalse(FileUtils.isFileOlder(newFile, offsetDateTime), "New File - Older - OffsetDateTime"); 1766 assertFalse(FileUtils.isFileOlder(newFile, localDateTime), "New File - Older - LocalDateTime"); 1767 assertFalse(FileUtils.isFileOlder(newFile, localDateTime, ZoneId.systemDefault()), "New File - Older - LocalDateTime,ZoneId"); 1768 assertTrue(FileUtils.isFileOlder(newFile, localDate), "New File - Older - LocalDate"); 1769 assertFalse(FileUtils.isFileOlder(newFile, localDate, localTime0), "New File - Older - LocalDate,LocalTime"); 1770 assertFalse(FileUtils.isFileOlder(newFile, localDate, offsetTime0), "New File - Older - LocalDate,OffsetTime"); 1771 assertTrue(FileUtils.isFileOlder(newFile, localDatePlusDay), "New File - Older - LocalDate plus one day"); 1772 assertTrue(FileUtils.isFileOlder(newFile, localDatePlusDay, localTime0), "New File - Older - LocalDate plus one day,LocalTime"); 1773 assertTrue(FileUtils.isFileOlder(newFile, localDatePlusDay, offsetTime0), "New File - Older - LocalDate plus one day,OffsetTime"); 1774 1775 assertFalse(FileUtils.isFileOlder(invalidFile, refFile), "Invalid - Older - File"); 1776 assertThrows(IllegalArgumentException.class, () -> FileUtils.isFileOlder(newFile, invalidFile)); 1777 1778 // Null File 1779 assertThrows(NullPointerException.class, () -> FileUtils.isFileNewer(null, now)); 1780 1781 // Null reference File 1782 assertThrows(NullPointerException.class, () -> FileUtils.isFileNewer(oldFile, (File) null)); 1783 1784 // Invalid reference File 1785 assertThrows(IllegalArgumentException.class, () -> FileUtils.isFileNewer(oldFile, invalidFile)); 1786 1787 // Null reference Date 1788 assertThrows(NullPointerException.class, () -> FileUtils.isFileNewer(oldFile, (Date) null)); 1789 1790 // ----- Test isFileOlder() exceptions ----- 1791 // Null File 1792 assertThrows(NullPointerException.class, () -> FileUtils.isFileOlder(null, now)); 1793 1794 // Null reference File 1795 assertThrows(NullPointerException.class, () -> FileUtils.isFileOlder(oldFile, (File) null)); 1796 1797 // Null reference Date 1798 assertThrows(NullPointerException.class, () -> FileUtils.isFileOlder(oldFile, (Date) null)); 1799 1800 // Invalid reference File 1801 assertThrows(IllegalArgumentException.class, () -> FileUtils.isFileOlder(oldFile, invalidFile)); 1802 } 1803 1804 @Test 1805 public void testIsRegularFile() throws IOException { 1806 assertFalse(FileUtils.isRegularFile(null)); 1807 1808 assertFalse(FileUtils.isRegularFile(tempDirFile)); 1809 assertTrue(FileUtils.isRegularFile(testFile1)); 1810 1811 Files.delete(testFile1.toPath()); 1812 assertFalse(FileUtils.isRegularFile(testFile1)); 1813 } 1814 1815 @Test 1816 public void testIterateFiles() throws Exception { 1817 final File srcDir = tempDirFile; 1818 final File subDir = new File(srcDir, "list_test"); 1819 final File subSubDir = new File(subDir, "subSubDir"); 1820 final File notSubSubDir = new File(subDir, "notSubSubDir"); 1821 assertTrue(subDir.mkdir()); 1822 assertTrue(subSubDir.mkdir()); 1823 assertTrue(notSubSubDir.mkdir()); 1824 Iterator<File> iterator = null; 1825 try { 1826 // Need list to be appendable 1827 final List<String> expectedFileNames = new ArrayList<>( 1828 Arrays.asList("a.txt", "b.txt", "c.txt", "d.txt", "e.txt", "f.txt")); 1829 final int[] fileSizes = {123, 234, 345, 456, 678, 789}; 1830 assertEquals(expectedFileNames.size(), fileSizes.length); 1831 Collections.sort(expectedFileNames); 1832 Arrays.sort(fileSizes); 1833 for (int i = 0; i < fileSizes.length; ++i) { 1834 TestUtils.generateTestData(new File(subDir, expectedFileNames.get(i)), fileSizes[i]); 1835 } 1836 // 1837 final String subSubFileName = "z.txt"; 1838 TestUtils.generateTestData(new File(subSubDir, subSubFileName), 1); 1839 expectedFileNames.add(subSubFileName); 1840 // 1841 final String notSubSubFileName = "not.txt"; 1842 TestUtils.generateTestData(new File(notSubSubDir, notSubSubFileName), 1); 1843 1844 final WildcardFileFilter allFilesFileFilter = new WildcardFileFilter("*.*"); 1845 final NameFileFilter dirFilter = new NameFileFilter("subSubDir"); 1846 iterator = FileUtils.iterateFiles(subDir, allFilesFileFilter, dirFilter); 1847 1848 final Map<String, String> matchedFileNames = new HashMap<>(); 1849 final List<String> actualFileNames = new ArrayList<>(); 1850 1851 while (iterator.hasNext()) { 1852 boolean found = false; 1853 final String fileName = iterator.next().getName(); 1854 actualFileNames.add(fileName); 1855 1856 for (int j = 0; !found && j < expectedFileNames.size(); ++j) { 1857 final String expectedFileName = expectedFileNames.get(j); 1858 if (expectedFileName.equals(fileName)) { 1859 matchedFileNames.put(expectedFileName, expectedFileName); 1860 found = true; 1861 } 1862 } 1863 } 1864 assertEquals(expectedFileNames.size(), matchedFileNames.size()); 1865 Collections.sort(actualFileNames); 1866 assertEquals(expectedFileNames, actualFileNames); 1867 } finally { 1868 consumeRemaining(iterator); 1869 notSubSubDir.delete(); 1870 subSubDir.delete(); 1871 subDir.delete(); 1872 } 1873 } 1874 1875 @Test 1876 public void testIterateFilesAndDirs() throws IOException { 1877 final File srcDir = tempDirFile; 1878 // temporaryFolder/srcDir 1879 // - subdir1 1880 // -- subdir2 1881 // --- a.txt 1882 // --- subdir3 1883 // --- subdir4 1884 final File subDir1 = new File(srcDir, "subdir1"); 1885 final File subDir2 = new File(subDir1, "subdir2"); 1886 final File subDir3 = new File(subDir2, "subdir3"); 1887 final File subDir4 = new File(subDir2, "subdir4"); 1888 assertTrue(subDir1.mkdir()); 1889 assertTrue(subDir2.mkdir()); 1890 assertTrue(subDir3.mkdir()); 1891 assertTrue(subDir4.mkdir()); 1892 final File someFile = new File(subDir2, "a.txt"); 1893 final WildcardFileFilter fileFilterAllFiles = new WildcardFileFilter("*.*"); 1894 final WildcardFileFilter fileFilterAllDirs = new WildcardFileFilter("*"); 1895 final WildcardFileFilter fileFilterExtTxt = new WildcardFileFilter("*.txt"); 1896 try { 1897 try (OutputStream output = new BufferedOutputStream(Files.newOutputStream(someFile.toPath()))) { 1898 TestUtils.generateTestData(output, 100); 1899 } 1900 // 1901 // "*.*" and "*" 1902 Collection<File> expectedFilesAndDirs = Arrays.asList(subDir1, subDir2, someFile, subDir3, subDir4); 1903 iterateFilesAndDirs(subDir1, fileFilterAllFiles, fileFilterAllDirs, expectedFilesAndDirs); 1904 // 1905 // "*.txt" and "*" 1906 final int filesCount; 1907 expectedFilesAndDirs = Arrays.asList(subDir1, subDir2, someFile, subDir3, subDir4); 1908 iterateFilesAndDirs(subDir1, fileFilterExtTxt, fileFilterAllDirs, expectedFilesAndDirs); 1909 // 1910 // "*.*" and "subdir2" 1911 expectedFilesAndDirs = Arrays.asList(subDir1, subDir2, someFile); 1912 iterateFilesAndDirs(subDir1, fileFilterAllFiles, new NameFileFilter("subdir2"), expectedFilesAndDirs); 1913 // 1914 // "*.txt" and "subdir2" 1915 expectedFilesAndDirs = Arrays.asList(subDir1, subDir2, someFile); 1916 iterateFilesAndDirs(subDir1, fileFilterExtTxt, new NameFileFilter("subdir2"), expectedFilesAndDirs); 1917 } finally { 1918 someFile.delete(); 1919 subDir4.delete(); 1920 subDir3.delete(); 1921 subDir2.delete(); 1922 subDir1.delete(); 1923 } 1924 } 1925 1926 @Test 1927 public void testIterateFilesOnlyNoDirs() throws IOException { 1928 final File directory = tempDirFile; 1929 assertTrue(new File(directory, "TEST").mkdir()); 1930 assertTrue(new File(directory, "test.txt").createNewFile()); 1931 1932 final IOFileFilter filter = new WildcardFileFilter("*", IOCase.INSENSITIVE); 1933 FileUtils.iterateFiles(directory, filter, null).forEachRemaining(file -> assertFalse(file.isDirectory(), file::getAbsolutePath)); 1934 } 1935 1936 @Test 1937 public void testListFiles() throws Exception { 1938 final File srcDir = tempDirFile; 1939 final File subDir = new File(srcDir, "list_test"); 1940 final File subDir2 = new File(subDir, "subdir"); 1941 subDir.mkdir(); 1942 subDir2.mkdir(); 1943 try { 1944 1945 final String[] expectedFileNames = {"a.txt", "b.txt", "c.txt", "d.txt", "e.txt", "f.txt"}; 1946 final int[] fileSizes = {123, 234, 345, 456, 678, 789}; 1947 1948 for (int i = 0; i < expectedFileNames.length; ++i) { 1949 final File theFile = new File(subDir, expectedFileNames[i]); 1950 if (!theFile.getParentFile().exists()) { 1951 fail("Cannot create file " + theFile + " as the parent directory does not exist"); 1952 } 1953 try (final BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(theFile.toPath()))) { 1954 TestUtils.generateTestData(output, fileSizes[i]); 1955 } 1956 } 1957 1958 final Collection<File> actualFiles = FileUtils.listFiles(subDir, new WildcardFileFilter("*.*"), new WildcardFileFilter("*")); 1959 1960 final int count = actualFiles.size(); 1961 final Object[] fileObjs = actualFiles.toArray(); 1962 1963 assertEquals(expectedFileNames.length, actualFiles.size(), actualFiles::toString); 1964 1965 final Map<String, String> foundFileNames = new HashMap<>(); 1966 1967 for (int i = 0; i < count; ++i) { 1968 boolean found = false; 1969 for (int j = 0; !found && j < expectedFileNames.length; ++j) { 1970 if (expectedFileNames[j].equals(((File) fileObjs[i]).getName())) { 1971 foundFileNames.put(expectedFileNames[j], expectedFileNames[j]); 1972 found = true; 1973 } 1974 } 1975 } 1976 1977 assertEquals(foundFileNames.size(), expectedFileNames.length, foundFileNames::toString); 1978 } finally { 1979 subDir.delete(); 1980 } 1981 } 1982 1983 @Test 1984 public void testListFilesOnlyNoDirs() throws IOException { 1985 final File directory = tempDirFile; 1986 assertTrue(new File(directory, "TEST").mkdir()); 1987 assertTrue(new File(directory, "test.txt").createNewFile()); 1988 1989 final IOFileFilter filter = new WildcardFileFilter("*", IOCase.INSENSITIVE); 1990 for (final File file : FileUtils.listFiles(directory, filter, null)) { 1991 assertFalse(file.isDirectory(), file::getAbsolutePath); 1992 } 1993 } 1994 1995 @Test 1996 public void testListFilesWithDirs() throws IOException { 1997 final File srcDir = tempDirFile; 1998 1999 final File subDir1 = new File(srcDir, "subdir"); 2000 final File subDir2 = new File(subDir1, "subdir2"); 2001 subDir1.mkdir(); 2002 subDir2.mkdir(); 2003 try { 2004 final File someFile = new File(subDir2, "a.txt"); 2005 if (!someFile.getParentFile().exists()) { 2006 fail("Cannot create file " + someFile + " as the parent directory does not exist"); 2007 } 2008 try (final BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(someFile.toPath()))) { 2009 TestUtils.generateTestData(output, 100); 2010 } 2011 2012 final File subDir3 = new File(subDir2, "subdir3"); 2013 subDir3.mkdir(); 2014 2015 final Collection<File> files = FileUtils.listFilesAndDirs(subDir1, new WildcardFileFilter("*.*"), 2016 new WildcardFileFilter("*")); 2017 2018 assertEquals(4, files.size()); 2019 assertTrue(files.contains(subDir1), "Should contain the directory."); 2020 assertTrue(files.contains(subDir2), "Should contain the directory."); 2021 assertTrue(files.contains(someFile), "Should contain the file."); 2022 assertTrue(files.contains(subDir3), "Should contain the directory."); 2023 } finally { 2024 subDir1.delete(); 2025 } 2026 } 2027 2028 @Test 2029 public void testMoveDirectory_CopyDelete() throws Exception { 2030 2031 final File dir = tempDirFile; 2032 final File src = new File(dir, "testMoveDirectory2Source") { 2033 private static final long serialVersionUID = 1L; 2034 2035 // Force renameTo to fail 2036 @Override 2037 public boolean renameTo(final File dest) { 2038 return false; 2039 } 2040 }; 2041 final File testDir = new File(src, "foo"); 2042 final File testFile = new File(testDir, "bar"); 2043 testDir.mkdirs(); 2044 if (!testFile.getParentFile().exists()) { 2045 fail("Cannot create file " + testFile 2046 + " as the parent directory does not exist"); 2047 } 2048 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(testFile.toPath()))) { 2049 TestUtils.generateTestData(output, 0); 2050 } 2051 final File destination = new File(dir, "testMoveDirectory1Dest"); 2052 FileUtils.deleteDirectory(destination); 2053 2054 // Move the directory 2055 FileUtils.moveDirectory(src, destination); 2056 2057 // Check results 2058 assertTrue(destination.exists(), "Check Exist"); 2059 assertFalse(src.exists(), "Original deleted"); 2060 final File movedDir = new File(destination, testDir.getName()); 2061 final File movedFile = new File(movedDir, testFile.getName()); 2062 assertTrue(movedDir.exists(), "Check dir moved"); 2063 assertTrue(movedFile.exists(), "Check file moved"); 2064 } 2065 2066 @Test 2067 public void testMoveDirectory_Errors() throws Exception { 2068 assertThrows(NullPointerException.class, () -> FileUtils.moveDirectory(null, new File("foo"))); 2069 assertThrows(NullPointerException.class, () -> FileUtils.moveDirectory(new File("foo"), null)); 2070 assertThrows(FileNotFoundException.class, () -> FileUtils.moveDirectory(new File("nonexistant"), new File("foo"))); 2071 2072 final File testFile = new File(tempDirFile, "testMoveDirectoryFile"); 2073 if (!testFile.getParentFile().exists()) { 2074 fail("Cannot create file " + testFile + " as the parent directory does not exist"); 2075 } 2076 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(testFile.toPath()))) { 2077 TestUtils.generateTestData(output, 0); 2078 } 2079 assertThrows(IllegalArgumentException.class, () -> FileUtils.moveDirectory(testFile, new File("foo"))); 2080 final File testSrcFile = new File(tempDirFile, "testMoveDirectorySource"); 2081 final File testDestFile = new File(tempDirFile, "testMoveDirectoryDest"); 2082 testSrcFile.mkdir(); 2083 testDestFile.mkdir(); 2084 assertThrows(FileExistsException.class, () -> FileUtils.moveDirectory(testSrcFile, testDestFile), 2085 "Expected FileExistsException when dest already exists"); 2086 2087 } 2088 2089 @Test 2090 public void testMoveDirectory_Rename() throws Exception { 2091 final File dir = tempDirFile; 2092 final File src = new File(dir, "testMoveDirectory1Source"); 2093 final File testDir = new File(src, "foo"); 2094 final File testFile = new File(testDir, "bar"); 2095 testDir.mkdirs(); 2096 if (!testFile.getParentFile().exists()) { 2097 fail("Cannot create file " + testFile 2098 + " as the parent directory does not exist"); 2099 } 2100 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(testFile.toPath()))) { 2101 TestUtils.generateTestData(output, 0); 2102 } 2103 final File destination = new File(dir, "testMoveDirectory1Dest"); 2104 FileUtils.deleteDirectory(destination); 2105 2106 // Move the directory 2107 FileUtils.moveDirectory(src, destination); 2108 2109 // Check results 2110 assertTrue(destination.exists(), "Check Exist"); 2111 assertFalse(src.exists(), "Original deleted"); 2112 final File movedDir = new File(destination, testDir.getName()); 2113 final File movedFile = new File(movedDir, testFile.getName()); 2114 assertTrue(movedDir.exists(), "Check dir moved"); 2115 assertTrue(movedFile.exists(), "Check file moved"); 2116 } 2117 2118 @Test 2119 public void testMoveDirectoryToDirectory() throws Exception { 2120 final File dir = tempDirFile; 2121 final File src = new File(dir, "testMoveDirectory1Source"); 2122 final File testChildDir = new File(src, "foo"); 2123 final File testFile = new File(testChildDir, "bar"); 2124 testChildDir.mkdirs(); 2125 if (!testFile.getParentFile().exists()) { 2126 fail("Cannot create file " + testFile 2127 + " as the parent directory does not exist"); 2128 } 2129 try (final OutputStream output = new BufferedOutputStream(Files.newOutputStream(testFile.toPath()))) { 2130 TestUtils.generateTestData(output, 0); 2131 } 2132 final File destDir = new File(dir, "testMoveDirectory1Dest"); 2133 FileUtils.deleteDirectory(destDir); 2134 assertFalse(destDir.exists(), "Check Exist before"); 2135 2136 // Move the directory 2137 FileUtils.moveDirectoryToDirectory(src, destDir, true); 2138 2139 // Check results 2140 assertTrue(destDir.exists(), "Check Exist after"); 2141 assertFalse(src.exists(), "Original deleted"); 2142 final File movedDir = new File(destDir, src.getName()); 2143 final File movedChildDir = new File(movedDir, testChildDir.getName()); 2144 final File movedFile = new File(movedChildDir, testFile.getName()); 2145 assertTrue(movedDir.exists(), "Check dir moved"); 2146 assertTrue(movedChildDir.exists(), "Check child dir moved"); 2147 assertTrue(movedFile.exists(), "Check file moved"); 2148 } 2149 2150 @Test 2151 public void testMoveDirectoryToDirectory_Errors() throws Exception { 2152 assertThrows(NullPointerException.class, () -> FileUtils.moveDirectoryToDirectory(null, new File("foo"), true)); 2153 assertThrows(NullPointerException.class, () -> FileUtils.moveDirectoryToDirectory(new File("foo"), null, true)); 2154 final File testFile1 = new File(tempDirFile, "testMoveFileFile1"); 2155 final File testFile2 = new File(tempDirFile, "testMoveFileFile2"); 2156 if (!testFile1.getParentFile().exists()) { 2157 fail("Cannot create file " + testFile1 + " as the parent directory does not exist"); 2158 } 2159 try (final BufferedOutputStream output1 = new BufferedOutputStream(Files.newOutputStream(testFile1.toPath()))) { 2160 TestUtils.generateTestData(output1, 0); 2161 } 2162 if (!testFile2.getParentFile().exists()) { 2163 fail("Cannot create file " + testFile2 + " as the parent directory does not exist"); 2164 } 2165 try (final BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(testFile2.toPath()))) { 2166 TestUtils.generateTestData(output, 0); 2167 } 2168 assertThrows(IOException.class, () -> FileUtils.moveDirectoryToDirectory(testFile1, testFile2, true)); 2169 2170 final File nonexistant = new File(tempDirFile, "testMoveFileNonExistant"); 2171 assertThrows(IOException.class, () -> FileUtils.moveDirectoryToDirectory(testFile1, nonexistant, false)); 2172 } 2173 2174 @Test 2175 public void testMoveFile_CopyDelete() throws Exception { 2176 final File destination = new File(tempDirFile, "move2.txt"); 2177 final File src = new File(testFile1.getAbsolutePath()) { 2178 private static final long serialVersionUID = 1L; 2179 2180 // Force renameTo to fail, as if destination is on another 2181 // filesystem 2182 @Override 2183 public boolean renameTo(final File f) { 2184 return false; 2185 } 2186 }; 2187 FileUtils.moveFile(src, destination); 2188 assertTrue(destination.exists(), "Check Exist"); 2189 assertFalse(src.exists(), "Original deleted"); 2190 } 2191 2192 @Test 2193 public void testMoveFile_CopyDelete_Failed() { 2194 final File destination = new File(tempDirFile, "move3.txt"); 2195 final File src = new File(testFile1.getAbsolutePath()) { 2196 private static final long serialVersionUID = 1L; 2197 2198 // Force delete failure 2199 @Override 2200 public boolean delete() { 2201 return false; 2202 } 2203 2204 // Force renameTo to fail, as if destination is on another 2205 // filesystem 2206 @Override 2207 public boolean renameTo(final File f) { 2208 return false; 2209 } 2210 2211 }; 2212 assertThrows(IOException.class, () -> FileUtils.moveFile(src, destination)); 2213 // expected 2214 assertFalse(destination.exists(), "Check Rollback"); 2215 assertTrue(src.exists(), "Original exists"); 2216 } 2217 2218 @Test 2219 public void testMoveFile_CopyDelete_WithFileDatePreservation() throws Exception { 2220 final File destination = new File(tempDirFile, "move2.txt"); 2221 2222 backDateFile10Minutes(testFile1); // set test file back 10 minutes 2223 2224 final File src = new File(testFile1.getAbsolutePath()) { 2225 private static final long serialVersionUID = 1L; 2226 2227 // Force renameTo to fail, as if destination is on another 2228 // filesystem 2229 @Override 2230 public boolean renameTo(final File f) { 2231 return false; 2232 } 2233 }; 2234 final long expected = getLastModifiedMillis(testFile1); 2235 2236 FileUtils.moveFile(src, destination, StandardCopyOption.COPY_ATTRIBUTES); 2237 assertTrue(destination.exists(), "Check Exist"); 2238 assertFalse(src.exists(), "Original deleted"); 2239 2240 final long destLastMod = getLastModifiedMillis(destination); 2241 final long delta = destLastMod - expected; 2242 assertEquals(expected, destLastMod, "Check last modified date same as input, delta " + delta); 2243 } 2244 2245 @Test 2246 public void testMoveFile_CopyDelete_WithoutFileDatePreservation() throws Exception { 2247 final File destination = new File(tempDirFile, "move2.txt"); 2248 2249 backDateFile10Minutes(testFile1); // set test file back 10 minutes 2250 2251 // destination file time should not be less than this (allowing for granularity) 2252 final long nowMillis = System.currentTimeMillis() - 1000L; 2253 2254 final File src = new File(testFile1.getAbsolutePath()) { 2255 private static final long serialVersionUID = 1L; 2256 2257 // Force renameTo to fail, as if destination is on another 2258 // filesystem 2259 @Override 2260 public boolean renameTo(final File f) { 2261 return false; 2262 } 2263 }; 2264 final long unexpectedMillis = getLastModifiedMillis(testFile1); 2265 2266 FileUtils.moveFile(src, destination, PathUtils.EMPTY_COPY_OPTIONS); 2267 assertTrue(destination.exists(), "Check Exist"); 2268 assertFalse(src.exists(), "Original deleted"); 2269 2270 // On Windows, the last modified time is copied by default. 2271 if (!SystemUtils.IS_OS_WINDOWS) { 2272 final long destLastModMillis = getLastModifiedMillis(destination); 2273 final long deltaMillis = destLastModMillis - unexpectedMillis; 2274 assertNotEquals(unexpectedMillis, destLastModMillis, 2275 "Check last modified date not same as input, delta " + deltaMillis); 2276 assertTrue(destLastModMillis > nowMillis, 2277 destLastModMillis + " > " + nowMillis + " (delta " + deltaMillis + ")"); 2278 } 2279 } 2280 2281 @Test 2282 public void testMoveFile_Errors() throws Exception { 2283 assertThrows(NullPointerException.class, () -> FileUtils.moveFile(null, new File("foo"))); 2284 assertThrows(NullPointerException.class, () -> FileUtils.moveFile(new File("foo"), null)); 2285 assertThrows(FileNotFoundException.class, () -> FileUtils.moveFile(new File("nonexistant"), new File("foo"))); 2286 assertThrows(IllegalArgumentException.class, () -> FileUtils.moveFile(tempDirFile, new File("foo"))); 2287 final File testSourceFile = new File(tempDirFile, "testMoveFileSource"); 2288 final File testDestFile = new File(tempDirFile, "testMoveFileSource"); 2289 if (!testSourceFile.getParentFile().exists()) { 2290 fail("Cannot create file " + testSourceFile + " as the parent directory does not exist"); 2291 } 2292 final BufferedOutputStream output1 = new BufferedOutputStream(Files.newOutputStream(testSourceFile.toPath())); 2293 try { 2294 TestUtils.generateTestData(output1, 0); 2295 } finally { 2296 IOUtils.closeQuietly(output1); 2297 } 2298 assertTrue(testDestFile.getParentFile().exists(), () -> "Cannot create file " + testDestFile + " as the parent directory does not exist"); 2299 final BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(testDestFile.toPath())); 2300 try { 2301 TestUtils.generateTestData(output, 0); 2302 } finally { 2303 IOUtils.closeQuietly(output); 2304 } 2305 assertThrows(FileExistsException.class, () -> FileUtils.moveFile(testSourceFile, testDestFile), 2306 "Expected FileExistsException when dest already exists"); 2307 } 2308 2309 @Test 2310 public void testMoveFile_Rename() throws Exception { 2311 final File destination = new File(tempDirFile, "move1.txt"); 2312 2313 FileUtils.moveFile(testFile1, destination); 2314 assertTrue(destination.exists(), "Check Exist"); 2315 assertFalse(testFile1.exists(), "Original deleted"); 2316 } 2317 2318 @Test 2319 public void testMoveFileToDirectory() throws Exception { 2320 final File destDir = new File(tempDirFile, "moveFileDestDir"); 2321 final File movedFile = new File(destDir, testFile1.getName()); 2322 assertFalse(destDir.exists(), "Check Exist before"); 2323 assertFalse(movedFile.exists(), "Check Exist before"); 2324 2325 FileUtils.moveFileToDirectory(testFile1, destDir, true); 2326 assertTrue(movedFile.exists(), "Check Exist after"); 2327 assertFalse(testFile1.exists(), "Original deleted"); 2328 } 2329 2330 @Test 2331 public void testMoveFileToDirectory_Errors() throws Exception { 2332 assertThrows(NullPointerException.class, () -> FileUtils.moveFileToDirectory(null, new File("foo"), true)); 2333 assertThrows(NullPointerException.class, () -> FileUtils.moveFileToDirectory(new File("foo"), null, true)); 2334 final File testFile1 = new File(tempDirFile, "testMoveFileFile1"); 2335 final File testFile2 = new File(tempDirFile, "testMoveFileFile2"); 2336 if (!testFile1.getParentFile().exists()) { 2337 fail("Cannot create file " + testFile1 + " as the parent directory does not exist"); 2338 } 2339 try (final BufferedOutputStream output1 = new BufferedOutputStream(Files.newOutputStream(testFile1.toPath()))) { 2340 TestUtils.generateTestData(output1, 0); 2341 } 2342 if (!testFile2.getParentFile().exists()) { 2343 fail("Cannot create file " + testFile2 + " as the parent directory does not exist"); 2344 } 2345 final BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(testFile2.toPath())); 2346 try { 2347 TestUtils.generateTestData(output, 0); 2348 } finally { 2349 IOUtils.closeQuietly(output); 2350 } 2351 assertThrows(IllegalArgumentException.class, () -> FileUtils.moveFileToDirectory(testFile1, testFile2, true)); 2352 2353 final File nonexistant = new File(tempDirFile, "testMoveFileNonExistant"); 2354 assertThrows(IOException.class, () -> FileUtils.moveFileToDirectory(testFile1, nonexistant, false)); 2355 } 2356 2357 @Test 2358 public void testMoveToDirectory() throws Exception { 2359 final File destDir = new File(tempDirFile, "testMoveToDirectoryDestDir"); 2360 final File testDir = new File(tempDirFile, "testMoveToDirectoryTestDir"); 2361 final File testFile = new File(tempDirFile, "testMoveToDirectoryTestFile"); 2362 testDir.mkdirs(); 2363 if (!testFile.getParentFile().exists()) { 2364 fail("Cannot create file " + testFile 2365 + " as the parent directory does not exist"); 2366 } 2367 final BufferedOutputStream output = 2368 new BufferedOutputStream(Files.newOutputStream(testFile.toPath())); 2369 try { 2370 TestUtils.generateTestData(output, 0); 2371 } finally { 2372 IOUtils.closeQuietly(output); 2373 } 2374 final File movedFile = new File(destDir, testFile.getName()); 2375 final File movedDir = new File(destDir, testFile.getName()); 2376 2377 assertFalse(movedFile.exists(), "Check File Doesnt exist"); 2378 assertFalse(movedDir.exists(), "Check Dir Doesnt exist"); 2379 2380 // Test moving a file 2381 FileUtils.moveToDirectory(testFile, destDir, true); 2382 assertTrue(movedFile.exists(), "Check File exists"); 2383 assertFalse(testFile.exists(), "Check Original File doesn't exist"); 2384 2385 // Test moving a directory 2386 FileUtils.moveToDirectory(testDir, destDir, true); 2387 assertTrue(movedDir.exists(), "Check Dir exists"); 2388 assertFalse(testDir.exists(), "Check Original Dir doesn't exist"); 2389 } 2390 2391 @Test 2392 public void testMoveToDirectory_Errors() throws Exception { 2393 assertThrows(NullPointerException.class, () -> FileUtils.moveDirectoryToDirectory(null, new File("foo"), true)); 2394 assertThrows(NullPointerException.class, () -> FileUtils.moveDirectoryToDirectory(new File("foo"), null, true)); 2395 final File nonexistant = new File(tempDirFile, "nonexistant"); 2396 final File destDir = new File(tempDirFile, "MoveToDirectoryDestDir"); 2397 assertThrows(IOException.class, () -> FileUtils.moveToDirectory(nonexistant, destDir, true), "Expected IOException when source does not exist"); 2398 2399 } 2400 2401 @Test 2402 public void testReadFileToByteArray() throws Exception { 2403 final File file = new File(tempDirFile, "read.txt"); 2404 Files.write(file.toPath(), new byte[] {11, 21, 31}); 2405 2406 final byte[] data = FileUtils.readFileToByteArray(file); 2407 assertEquals(3, data.length); 2408 assertEquals(11, data[0]); 2409 assertEquals(21, data[1]); 2410 assertEquals(31, data[2]); 2411 } 2412 2413 @Test 2414 public void testReadFileToStringWithDefaultEncoding() throws Exception { 2415 final File file = new File(tempDirFile, "read.obj"); 2416 final String fixture = "Hello /u1234"; 2417 Files.write(file.toPath(), fixture.getBytes()); 2418 2419 assertEquals(fixture, FileUtils.readFileToString(file)); 2420 } 2421 2422 @Test 2423 public void testReadFileToStringWithEncoding() throws Exception { 2424 final File file = new File(tempDirFile, "read.obj"); 2425 final byte[] text = "Hello /u1234".getBytes(StandardCharsets.UTF_8); 2426 Files.write(file.toPath(), text); 2427 2428 final String data = FileUtils.readFileToString(file, "UTF8"); 2429 assertEquals("Hello /u1234", data); 2430 } 2431 2432 @Test 2433 public void testReadLines() throws Exception { 2434 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2435 try { 2436 final String[] data = {"hello", "/u1234", "", "this is", "some text"}; 2437 TestUtils.createLineBasedFile(file, data); 2438 2439 final List<String> lines = FileUtils.readLines(file, UTF_8); 2440 assertEquals(Arrays.asList(data), lines); 2441 } finally { 2442 TestUtils.deleteFile(file); 2443 } 2444 } 2445 2446 @Test 2447 public void testSizeOf() throws Exception { 2448 final File file = new File(tempDirFile, getName()); 2449 2450 // Null argument 2451 assertThrows(NullPointerException.class, () -> FileUtils.sizeOf(null)); 2452 2453 // Non-existent file 2454 assertThrows(IllegalArgumentException.class, () -> FileUtils.sizeOf(file)); 2455 2456 // Creates file 2457 file.createNewFile(); 2458 2459 // New file 2460 assertEquals(0, FileUtils.sizeOf(file)); 2461 file.delete(); 2462 2463 // Existing file 2464 assertEquals(testFile1Size, FileUtils.sizeOf(testFile1), "Unexpected files size"); 2465 2466 // Existing directory 2467 assertEquals(TEST_DIRECTORY_SIZE, FileUtils.sizeOf(tempDirFile), "Unexpected directory size"); 2468 } 2469 2470 @Test 2471 public void testSizeOfAsBigInteger() throws Exception { 2472 final File file = new File(tempDirFile, getName()); 2473 2474 // Null argument 2475 assertThrows(NullPointerException.class, () -> FileUtils.sizeOfAsBigInteger(null)); 2476 // Non-existent file 2477 assertThrows(IllegalArgumentException.class, () -> FileUtils.sizeOfAsBigInteger(file)); 2478 2479 // Creates file 2480 file.createNewFile(); 2481 2482 // New file 2483 assertEquals(BigInteger.ZERO, FileUtils.sizeOfAsBigInteger(file)); 2484 file.delete(); 2485 2486 // Existing file 2487 assertEquals(BigInteger.valueOf(testFile1Size), FileUtils.sizeOfAsBigInteger(testFile1), 2488 "Unexpected files size"); 2489 2490 // Existing directory 2491 assertEquals(TEST_DIRECTORY_SIZE_BI, FileUtils.sizeOfAsBigInteger(tempDirFile), 2492 "Unexpected directory size"); 2493 } 2494 2495 @Test 2496 public void testSizeOfDirectory() throws Exception { 2497 final File file = new File(tempDirFile, getName()); 2498 2499 // Null argument 2500 assertThrows(NullPointerException.class, () -> FileUtils.sizeOfDirectory(null)); 2501 // Non-existent file 2502 assertThrows(IllegalArgumentException.class, () -> FileUtils.sizeOfAsBigInteger(file)); 2503 2504 // Creates file 2505 file.createNewFile(); 2506 2507 // Existing file 2508 assertThrows(IllegalArgumentException.class, () -> FileUtils.sizeOfDirectory(file)); 2509 2510 // Existing directory 2511 file.delete(); 2512 file.mkdir(); 2513 2514 // Create a cyclic symlink 2515 this.createCircularSymLink(file); 2516 2517 assertEquals(TEST_DIRECTORY_SIZE, FileUtils.sizeOfDirectory(file), "Unexpected directory size"); 2518 } 2519 2520 @Test 2521 public void testSizeOfDirectoryAsBigInteger() throws Exception { 2522 final File file = new File(tempDirFile, getName()); 2523 2524 // Null argument 2525 assertThrows(NullPointerException.class, () -> FileUtils.sizeOfDirectoryAsBigInteger(null)); 2526 // Non-existent file 2527 assertThrows(IllegalArgumentException.class, () -> FileUtils.sizeOfDirectoryAsBigInteger(file)); 2528 2529 // Creates file 2530 file.createNewFile(); 2531 2532 // Existing file 2533 assertThrows(IllegalArgumentException.class, () -> FileUtils.sizeOfDirectoryAsBigInteger(file)); 2534 2535 // Existing directory 2536 file.delete(); 2537 file.mkdir(); 2538 2539 createCircularSymLink(file); 2540 2541 assertEquals(TEST_DIRECTORY_SIZE_BI, FileUtils.sizeOfDirectoryAsBigInteger(file), "Unexpected directory size"); 2542 2543 // Existing directory which size is greater than zero 2544 file.delete(); 2545 file.mkdir(); 2546 2547 final File nonEmptyFile = new File(file, "nonEmptyFile" + System.nanoTime()); 2548 assertTrue(nonEmptyFile.getParentFile().exists(), () -> "Cannot create file " + nonEmptyFile + " as the parent directory does not exist"); 2549 final OutputStream output = new BufferedOutputStream(Files.newOutputStream(nonEmptyFile.toPath())); 2550 try { 2551 TestUtils.generateTestData(output, TEST_DIRECTORY_SIZE_GT_ZERO_BI.longValue()); 2552 } finally { 2553 IOUtils.closeQuietly(output); 2554 } 2555 2556 assertEquals(TEST_DIRECTORY_SIZE_GT_ZERO_BI, FileUtils.sizeOfDirectoryAsBigInteger(file), "Unexpected directory size"); 2557 2558 nonEmptyFile.delete(); 2559 file.delete(); 2560 } 2561 2562 @Test 2563 public void testToFile1() throws Exception { 2564 final URL url = new URL("file", null, "a/b/c/file.txt"); 2565 final File file = FileUtils.toFile(url); 2566 assertTrue(file.toString().contains("file.txt")); 2567 } 2568 2569 @Test 2570 public void testToFile2() throws Exception { 2571 final URL url = new URL("file", null, "a/b/c/file%20n%61me%2520.tx%74"); 2572 final File file = FileUtils.toFile(url); 2573 assertTrue(file.toString().contains("file name%20.txt")); 2574 } 2575 2576 @Test 2577 public void testToFile3() throws Exception { 2578 assertNull(FileUtils.toFile(null)); 2579 assertNull(FileUtils.toFile(new URL("http://jakarta.apache.org"))); 2580 } 2581 2582 @Test 2583 public void testToFile4() throws Exception { 2584 final URL url = new URL("file", null, "a/b/c/file%%20%me.txt%"); 2585 final File file = FileUtils.toFile(url); 2586 assertTrue(file.toString().contains("file% %me.txt%")); 2587 } 2588 2589 /* IO-252 */ 2590 @Test 2591 public void testToFile5() throws Exception { 2592 final URL url = new URL("file", null, "both%20are%20100%20%25%20true"); 2593 final File file = FileUtils.toFile(url); 2594 assertEquals("both are 100 % true", file.toString()); 2595 } 2596 2597 @Test 2598 public void testToFiles1() throws Exception { 2599 final URL[] urls = { 2600 new URL("file", null, "file1.txt"), 2601 new URL("file", null, "file2.txt"), 2602 }; 2603 final File[] files = FileUtils.toFiles(urls); 2604 2605 assertEquals(urls.length, files.length); 2606 assertTrue(files[0].toString().contains("file1.txt"), "File: " + files[0]); 2607 assertTrue(files[1].toString().contains("file2.txt"), "File: " + files[1]); 2608 } 2609 2610 @Test 2611 public void testToFiles2() throws Exception { 2612 final URL[] urls = { 2613 new URL("file", null, "file1.txt"), 2614 null, 2615 }; 2616 final File[] files = FileUtils.toFiles(urls); 2617 2618 assertEquals(urls.length, files.length); 2619 assertTrue(files[0].toString().contains("file1.txt"), "File: " + files[0]); 2620 assertNull(files[1], "File: " + files[1]); 2621 } 2622 2623 @Test 2624 public void testToFiles3() throws Exception { 2625 final URL[] urls = null; 2626 final File[] files = FileUtils.toFiles(urls); 2627 2628 assertEquals(0, files.length); 2629 } 2630 2631 @Test 2632 public void testToFiles3a() throws Exception { 2633 final URL[] urls = {}; // empty array 2634 final File[] files = FileUtils.toFiles(urls); 2635 2636 assertEquals(0, files.length); 2637 } 2638 2639 @Test 2640 public void testToFiles4() throws Exception { 2641 final URL[] urls = { 2642 new URL("file", null, "file1.txt"), 2643 new URL("http", "jakarta.apache.org", "file1.txt"), 2644 }; 2645 assertThrows(IllegalArgumentException.class, () -> FileUtils.toFiles(urls)); 2646 } 2647 2648 @Test 2649 public void testToFileUtf8() throws Exception { 2650 final URL url = new URL("file", null, "/home/%C3%A4%C3%B6%C3%BC%C3%9F"); 2651 final File file = FileUtils.toFile(url); 2652 assertTrue(file.toString().contains("\u00E4\u00F6\u00FC\u00DF")); 2653 } 2654 2655 @Test 2656 public void testTouch() throws IOException { 2657 assertThrows(NullPointerException.class, () -> FileUtils.touch(null)); 2658 2659 final File file = new File(tempDirFile, "touch.txt"); 2660 if (file.exists()) { 2661 file.delete(); 2662 } 2663 assertFalse(file.exists(), "Bad test: test file still exists"); 2664 FileUtils.touch(file); 2665 assertTrue(file.exists(), "FileUtils.touch() created file"); 2666 try (OutputStream out = Files.newOutputStream(file.toPath())) { 2667 assertEquals(0, file.length(), "Created empty file."); 2668 out.write(0); 2669 } 2670 assertEquals(1, file.length(), "Wrote one byte to file"); 2671 final long y2k = new GregorianCalendar(2000, 0, 1).getTime().getTime(); 2672 final boolean res = setLastModifiedMillis(file, y2k); // 0L fails on Win98 2673 assertTrue(res, "Bad test: set lastModified failed"); 2674 assertEquals(y2k, getLastModifiedMillis(file), "Bad test: set lastModified set incorrect value"); 2675 final long nowMillis = System.currentTimeMillis(); 2676 FileUtils.touch(file); 2677 assertEquals(1, file.length(), "FileUtils.touch() didn't empty the file."); 2678 assertNotEquals(y2k, getLastModifiedMillis(file), "FileUtils.touch() changed lastModified"); 2679 final int delta = 3000; 2680 assertTrue(getLastModifiedMillis(file) >= nowMillis - delta, "FileUtils.touch() changed lastModified to more than now-3s"); 2681 assertTrue(getLastModifiedMillis(file) <= nowMillis + delta, "FileUtils.touch() changed lastModified to less than now+3s"); 2682 } 2683 2684 @Test 2685 public void testToURLs1() throws Exception { 2686 final File[] files = { 2687 new File(tempDirFile, "file1.txt"), 2688 new File(tempDirFile, "file2.txt"), 2689 new File(tempDirFile, "test file.txt"), 2690 }; 2691 final URL[] urls = FileUtils.toURLs(files); 2692 2693 assertEquals(files.length, urls.length); 2694 assertTrue(urls[0].toExternalForm().startsWith("file:")); 2695 assertTrue(urls[0].toExternalForm().contains("file1.txt")); 2696 assertTrue(urls[1].toExternalForm().startsWith("file:")); 2697 assertTrue(urls[1].toExternalForm().contains("file2.txt")); 2698 2699 // Test escaped char 2700 assertTrue(urls[2].toExternalForm().startsWith("file:")); 2701 assertTrue(urls[2].toExternalForm().contains("test%20file.txt")); 2702 } 2703 2704 @Test 2705 public void testToURLs3a() throws Exception { 2706 final File[] files = {}; // empty array 2707 final URL[] urls = FileUtils.toURLs(files); 2708 2709 assertEquals(0, urls.length); 2710 } 2711 2712 @Test 2713 public void testWrite_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { 2714 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2715 FileUtils.writeStringToFile(file, "This line was there before you..."); 2716 2717 FileUtils.write(file, "this is brand new data", false); 2718 2719 final String expected = "this is brand new data"; 2720 final String actual = FileUtils.readFileToString(file); 2721 assertEquals(expected, actual); 2722 } 2723 2724 @Test 2725 public void testWrite_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { 2726 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2727 FileUtils.writeStringToFile(file, "This line was there before you..."); 2728 2729 FileUtils.write(file, "this is brand new data", true); 2730 2731 final String expected = "This line was there before you..." 2732 + "this is brand new data"; 2733 final String actual = FileUtils.readFileToString(file); 2734 assertEquals(expected, actual); 2735 } 2736 2737 @Test 2738 public void testWriteByteArrayToFile() throws Exception { 2739 final File file = new File(tempDirFile, "write.obj"); 2740 final byte[] data = {11, 21, 31}; 2741 FileUtils.writeByteArrayToFile(file, data); 2742 TestUtils.assertEqualContent(data, file); 2743 } 2744 2745 @Test 2746 public void testWriteByteArrayToFile_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { 2747 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2748 FileUtils.writeStringToFile(file, "This line was there before you..."); 2749 2750 FileUtils.writeByteArrayToFile(file, "this is brand new data".getBytes(), false); 2751 2752 final String expected = "this is brand new data"; 2753 final String actual = FileUtils.readFileToString(file); 2754 assertEquals(expected, actual); 2755 } 2756 2757 @Test 2758 public void testWriteByteArrayToFile_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { 2759 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2760 FileUtils.writeStringToFile(file, "This line was there before you..."); 2761 2762 FileUtils.writeByteArrayToFile(file, "this is brand new data".getBytes(), true); 2763 2764 final String expected = "This line was there before you..." 2765 + "this is brand new data"; 2766 final String actual = FileUtils.readFileToString(file); 2767 assertEquals(expected, actual); 2768 } 2769 2770 @Test 2771 public void testWriteByteArrayToFile_WithOffsetAndLength() throws Exception { 2772 final File file = new File(tempDirFile, "write.obj"); 2773 final byte[] data = {11, 21, 32, 41, 51}; 2774 final byte[] writtenData = new byte[3]; 2775 System.arraycopy(data, 1, writtenData, 0, 3); 2776 FileUtils.writeByteArrayToFile(file, data, 1, 3); 2777 TestUtils.assertEqualContent(writtenData, file); 2778 } 2779 2780 @Test 2781 public void testWriteByteArrayToFile_WithOffsetAndLength_WithAppendOptionTrue_ShouldDeletePreviousFileLines() throws Exception { 2782 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2783 FileUtils.writeStringToFile(file, "This line was there before you..."); 2784 2785 final byte[] data = "SKIP_THIS_this is brand new data_AND_SKIP_THIS".getBytes(StandardCharsets.UTF_8); 2786 FileUtils.writeByteArrayToFile(file, data, 10, 22, false); 2787 2788 final String expected = "this is brand new data"; 2789 final String actual = FileUtils.readFileToString(file, StandardCharsets.UTF_8); 2790 assertEquals(expected, actual); 2791 } 2792 2793 @Test 2794 public void testWriteByteArrayToFile_WithOffsetAndLength_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { 2795 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2796 FileUtils.writeStringToFile(file, "This line was there before you..."); 2797 2798 final byte[] data = "SKIP_THIS_this is brand new data_AND_SKIP_THIS".getBytes(StandardCharsets.UTF_8); 2799 FileUtils.writeByteArrayToFile(file, data, 10, 22, true); 2800 2801 final String expected = "This line was there before you..." + "this is brand new data"; 2802 final String actual = FileUtils.readFileToString(file, StandardCharsets.UTF_8); 2803 assertEquals(expected, actual); 2804 } 2805 2806 @Test 2807 public void testWriteCharSequence1() throws Exception { 2808 final File file = new File(tempDirFile, "write.txt"); 2809 FileUtils.write(file, "Hello /u1234", "UTF8"); 2810 final byte[] text = "Hello /u1234".getBytes(StandardCharsets.UTF_8); 2811 TestUtils.assertEqualContent(text, file); 2812 } 2813 2814 @Test 2815 public void testWriteCharSequence2() throws Exception { 2816 final File file = new File(tempDirFile, "write.txt"); 2817 FileUtils.write(file, "Hello /u1234", (String) null); 2818 final byte[] text = "Hello /u1234".getBytes(); 2819 TestUtils.assertEqualContent(text, file); 2820 } 2821 2822 2823 @Test 2824 public void testWriteLines_3arg_nullSeparator() throws Exception { 2825 final Object[] data = { 2826 "hello", new StringBuffer("world"), "", "this is", null, "some text"}; 2827 final List<Object> list = Arrays.asList(data); 2828 2829 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2830 FileUtils.writeLines(file, "US-ASCII", list); 2831 2832 final String expected = "hello" + System.lineSeparator() + "world" + System.lineSeparator() + 2833 System.lineSeparator() + "this is" + System.lineSeparator() + 2834 System.lineSeparator() + "some text" + System.lineSeparator(); 2835 final String actual = FileUtils.readFileToString(file, "US-ASCII"); 2836 assertEquals(expected, actual); 2837 } 2838 2839 @Test 2840 public void testWriteLines_3argsWithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { 2841 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2842 FileUtils.writeStringToFile(file, "This line was there before you..."); 2843 2844 final List<String> linesToAppend = Arrays.asList("my first line", "The second Line"); 2845 FileUtils.writeLines(file, linesToAppend, false); 2846 2847 final String expected = "my first line" 2848 + System.lineSeparator() + "The second Line" 2849 + System.lineSeparator(); 2850 final String actual = FileUtils.readFileToString(file); 2851 assertEquals(expected, actual); 2852 } 2853 2854 @Test 2855 public void testWriteLines_3argsWithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { 2856 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2857 FileUtils.writeStringToFile(file, "This line was there before you..."); 2858 2859 final List<String> linesToAppend = Arrays.asList("my first line", "The second Line"); 2860 FileUtils.writeLines(file, linesToAppend, true); 2861 2862 final String expected = "This line was there before you..." 2863 + "my first line" 2864 + System.lineSeparator() + "The second Line" 2865 + System.lineSeparator(); 2866 final String actual = FileUtils.readFileToString(file); 2867 assertEquals(expected, actual); 2868 } 2869 2870 @Test 2871 public void testWriteLines_4arg() throws Exception { 2872 final Object[] data = { 2873 "hello", new StringBuffer("world"), "", "this is", null, "some text"}; 2874 final List<Object> list = Arrays.asList(data); 2875 2876 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2877 FileUtils.writeLines(file, "US-ASCII", list, "*"); 2878 2879 final String expected = "hello*world**this is**some text*"; 2880 final String actual = FileUtils.readFileToString(file, "US-ASCII"); 2881 assertEquals(expected, actual); 2882 } 2883 2884 @Test 2885 public void testWriteLines_4arg_nullSeparator() throws Exception { 2886 final Object[] data = { 2887 "hello", new StringBuffer("world"), "", "this is", null, "some text"}; 2888 final List<Object> list = Arrays.asList(data); 2889 2890 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2891 FileUtils.writeLines(file, "US-ASCII", list, null); 2892 2893 final String expected = "hello" + System.lineSeparator() + "world" + System.lineSeparator() + 2894 System.lineSeparator() + "this is" + System.lineSeparator() + 2895 System.lineSeparator() + "some text" + System.lineSeparator(); 2896 final String actual = FileUtils.readFileToString(file, "US-ASCII"); 2897 assertEquals(expected, actual); 2898 } 2899 2900 @Test 2901 public void testWriteLines_4arg_Writer_nullData() throws Exception { 2902 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2903 FileUtils.writeLines(file, "US-ASCII", null, "*"); 2904 2905 assertEquals(0, file.length(), "Sizes differ"); 2906 } 2907 2908 @Test 2909 public void testWriteLines_4argsWithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { 2910 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2911 FileUtils.writeStringToFile(file, "This line was there before you..."); 2912 2913 final List<String> linesToAppend = Arrays.asList("my first line", "The second Line"); 2914 FileUtils.writeLines(file, linesToAppend, null, false); 2915 2916 final String expected = "my first line" 2917 + System.lineSeparator() + "The second Line" 2918 + System.lineSeparator(); 2919 final String actual = FileUtils.readFileToString(file); 2920 assertEquals(expected, actual); 2921 } 2922 2923 @Test 2924 public void testWriteLines_4argsWithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { 2925 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2926 FileUtils.writeStringToFile(file, "This line was there before you..."); 2927 2928 final List<String> linesToAppend = Arrays.asList("my first line", "The second Line"); 2929 FileUtils.writeLines(file, linesToAppend, null, true); 2930 2931 final String expected = "This line was there before you..." 2932 + "my first line" 2933 + System.lineSeparator() + "The second Line" 2934 + System.lineSeparator(); 2935 final String actual = FileUtils.readFileToString(file); 2936 assertEquals(expected, actual); 2937 } 2938 2939 @Test 2940 public void testWriteLines_5argsWithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { 2941 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2942 FileUtils.writeStringToFile(file, "This line was there before you..."); 2943 2944 final List<String> linesToAppend = Arrays.asList("my first line", "The second Line"); 2945 FileUtils.writeLines(file, null, linesToAppend, null, false); 2946 2947 final String expected = "my first line" 2948 + System.lineSeparator() + "The second Line" 2949 + System.lineSeparator(); 2950 final String actual = FileUtils.readFileToString(file); 2951 assertEquals(expected, actual); 2952 } 2953 2954 @Test 2955 public void testWriteLines_5argsWithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { 2956 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2957 FileUtils.writeStringToFile(file, "This line was there before you..."); 2958 2959 final List<String> linesToAppend = Arrays.asList("my first line", "The second Line"); 2960 FileUtils.writeLines(file, null, linesToAppend, null, true); 2961 2962 final String expected = "This line was there before you..." 2963 + "my first line" 2964 + System.lineSeparator() + "The second Line" 2965 + System.lineSeparator(); 2966 final String actual = FileUtils.readFileToString(file); 2967 assertEquals(expected, actual); 2968 } 2969 2970 @Test 2971 public void testWriteLinesEncoding_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { 2972 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2973 FileUtils.writeStringToFile(file, "This line was there before you..."); 2974 2975 final List<String> linesToAppend = Arrays.asList("my first line", "The second Line"); 2976 FileUtils.writeLines(file, null, linesToAppend, false); 2977 2978 final String expected = "my first line" 2979 + System.lineSeparator() + "The second Line" 2980 + System.lineSeparator(); 2981 final String actual = FileUtils.readFileToString(file); 2982 assertEquals(expected, actual); 2983 } 2984 2985 @Test 2986 public void testWriteLinesEncoding_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { 2987 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 2988 FileUtils.writeStringToFile(file, "This line was there before you..."); 2989 2990 final List<String> linesToAppend = Arrays.asList("my first line", "The second Line"); 2991 FileUtils.writeLines(file, null, linesToAppend, true); 2992 2993 final String expected = "This line was there before you..." 2994 + "my first line" 2995 + System.lineSeparator() + "The second Line" 2996 + System.lineSeparator(); 2997 final String actual = FileUtils.readFileToString(file); 2998 assertEquals(expected, actual); 2999 } 3000 3001 @Test 3002 public void testWriteStringToFile_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { 3003 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 3004 FileUtils.writeStringToFile(file, "This line was there before you..."); 3005 3006 FileUtils.writeStringToFile(file, "this is brand new data", false); 3007 3008 final String expected = "this is brand new data"; 3009 final String actual = FileUtils.readFileToString(file); 3010 assertEquals(expected, actual); 3011 } 3012 3013 @Test 3014 public void testWriteStringToFile_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { 3015 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 3016 FileUtils.writeStringToFile(file, "This line was there before you..."); 3017 3018 FileUtils.writeStringToFile(file, "this is brand new data", true); 3019 3020 final String expected = "This line was there before you..." 3021 + "this is brand new data"; 3022 final String actual = FileUtils.readFileToString(file); 3023 assertEquals(expected, actual); 3024 } 3025 3026 @Test 3027 public void testWriteStringToFileIntoNonExistentSubdir() throws Exception { 3028 final File file = new File(tempDirFile, "subdir/write.txt"); 3029 FileUtils.writeStringToFile(file, "Hello /u1234", (Charset) null); 3030 final byte[] text = "Hello /u1234".getBytes(); 3031 TestUtils.assertEqualContent(text, file); 3032 } 3033 3034 @Test 3035 public void testWriteStringToFileIntoSymlinkedDir() throws Exception { 3036 final Path symlinkDir = createTempSymlinkedRelativeDir(); 3037 3038 final File file = symlinkDir.resolve("file").toFile(); 3039 FileUtils.writeStringToFile(file, "Hello /u1234", StandardCharsets.UTF_8); 3040 3041 final byte[] text = "Hello /u1234".getBytes(); 3042 TestUtils.assertEqualContent(text, file); 3043 } 3044 3045 @Test 3046 public void testWriteStringToFileWithCharset() throws Exception { 3047 final File file = new File(tempDirFile, "write.txt"); 3048 FileUtils.writeStringToFile(file, "Hello /u1234", "UTF8"); 3049 final byte[] text = "Hello /u1234".getBytes(StandardCharsets.UTF_8); 3050 TestUtils.assertEqualContent(text, file); 3051 } 3052 3053 @Test 3054 public void testWriteStringToFileWithEncoding_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { 3055 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 3056 FileUtils.writeStringToFile(file, "This line was there before you..."); 3057 3058 FileUtils.writeStringToFile(file, "this is brand new data", (String) null, false); 3059 3060 final String expected = "this is brand new data"; 3061 final String actual = FileUtils.readFileToString(file); 3062 assertEquals(expected, actual); 3063 } 3064 3065 @Test 3066 public void testWriteStringToFileWithEncoding_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { 3067 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 3068 FileUtils.writeStringToFile(file, "This line was there before you..."); 3069 3070 FileUtils.writeStringToFile(file, "this is brand new data", (String) null, true); 3071 3072 final String expected = "This line was there before you..." 3073 + "this is brand new data"; 3074 final String actual = FileUtils.readFileToString(file); 3075 assertEquals(expected, actual); 3076 } 3077 3078 @Test 3079 public void testWriteStringToFileWithNullCharset() throws Exception { 3080 final File file = new File(tempDirFile, "write.txt"); 3081 FileUtils.writeStringToFile(file, "Hello /u1234", (Charset) null); 3082 final byte[] text = "Hello /u1234".getBytes(); 3083 TestUtils.assertEqualContent(text, file); 3084 } 3085 3086 @Test 3087 public void testWriteStringToFileWithNullStringCharset() throws Exception { 3088 final File file = new File(tempDirFile, "write.txt"); 3089 FileUtils.writeStringToFile(file, "Hello /u1234", (String) null); 3090 final byte[] text = "Hello /u1234".getBytes(); 3091 TestUtils.assertEqualContent(text, file); 3092 } 3093 3094 @Test 3095 public void testWriteWithEncoding_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception { 3096 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 3097 FileUtils.writeStringToFile(file, "This line was there before you..."); 3098 3099 FileUtils.write(file, "this is brand new data", (String) null, false); 3100 3101 final String expected = "this is brand new data"; 3102 final String actual = FileUtils.readFileToString(file); 3103 assertEquals(expected, actual); 3104 } 3105 3106 @Test 3107 public void testWriteWithEncoding_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception { 3108 final File file = TestUtils.newFile(tempDirFile, "lines.txt"); 3109 FileUtils.writeStringToFile(file, "This line was there before you..."); 3110 3111 FileUtils.write(file, "this is brand new data", (String) null, true); 3112 3113 final String expected = "This line was there before you..." 3114 + "this is brand new data"; 3115 final String actual = FileUtils.readFileToString(file); 3116 assertEquals(expected, actual); 3117 } 3118 3119 } 3120