1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 | package Torello.Java; import static Torello.Java.C.*; import java.util.*; import java.io.*; import java.nio.file.*; /** * Operating-System independent utilities for moving, copying and deleting files, or an entire * tree of files - using the <CODE>FileNode</CODE> class. * * <EMBED CLASS='external-html' DATA-FILE-ID=FILE_TRANSFER> */ @Torello.JavaDoc.StaticFunctional public class FileTransfer { private FileTransfer() { } /** * Copies the contents of one directory to another. Avoids copying files that do not pass * the filter test. This method will only copy files and will avoid copying any sub-directories * to the target directory. * * <DIV CLASS="EXAMPLE">{@code * // This loads all available files in the 'javadoc/' directory-tree for package Torello.HTML * FileNode fn = FileNode * .createRoot("javadoc/Torello/HTML/") * .loadTree(); * * // This will copy all '.html' files in directory 'javadoc/Torello/HTML/' to a temp directory. * // Log information (copy messages) will be printed to standard-out. If the programmer is on a * // UNIX system, they will be colorized using UNIX terminal color-codes. * // NOTE: The directory 'temp/' must have already been created. * FileTransfer.copy(fn, f -> f.name.endsWith(".html"), "temp/", System.out); * }</DIV> * * @param directory This must be a "directory" not a "file" instance of {@code public class * FileNode} or an exception shall be thrown. If this class is a directory, then every file that * is currently in this directory shall be copied to the {@code 'targetDirectory.'} This * parameter may not be null. * * @param filter This parameter may be null, but if it is not, each file will be tested by this * java-lambda for identifying whether or not it meets the "accept" or "reject" interface before * copying is performed. * * <BR /><BR /><B><SPAN STYLE="color: red;">FILTER PREDICATE BEHAVIOR:</SPAN></B> This filter * {@code Predicate<FileNode>} will return {@code TRUE} to indicate that the file in question * should be copied, and {@code FALSE} if no copy is needed. * * @param targetDirectory Where the files shall be copied. This must be a valid directory as * well, or else a {@code FileNotFoundException} shall throw. This method <B>will not</B> * create this directory if it does not exist. See method {@code java.io.File.mkdirs()} for * information on how to create files on the file-system. * * <BR /><BR /><B>NOTE:</B> It is expected that the last character in this {@code String} * contain a directory-separator character (on UNIX, this is the forward-slash ({@code '/'}) and * in MS-DOS, Windows this is the back-slash ({@code '\'}). If this character is not present, if * this {@code String} does not 'end-with' a {@code java.io.File.separator} then one will be * appended to the end of this {@code String}. * * @param a This parameter may be null, but if it is not, then debugging / logging / * informational messages will be sent to this output. * * <EMBED CLASS='external-html' DATA-FILE-ID=APPENDABLE> * * @return The number of files that were copied. * * @throws DirExpectedException If you pass a "file" instance of {@code class FileNode} to * parameter {@code 'directory.'} * * @throws WritableDirectoryException If the target-directory is not available to Java for * copying. * * @throws java.nio.file.NoSuchFileException This will be thrown if the logic which checks to * ensure that the source and target directories are not identical is unable to identify the * <I><B>real path name</B></I> of either the source or target directory. One such possible * situation where this would happen would be if the user applied the UNIX <B>tilda * ({@code '~'})</B> in either the {@code source} or {@code target} directory-name. * * @throws java.nio.file.InvalidPathException This will be thrown if {@code class * java.nio.file.Paths} is unable to instantiate a {@code java.nio.file.Path} for either the * source-directory (parameter {@code directory}), or the {@code targetDirectory}. * * @throws SameSourceAndTargetException This will be thrown if the source and target * directories are found to point to identical locations on the file-system. * * @throws IOException For any IO filesystem errors. * * @see #copyRecursive(FileNode, FileNodeFilter, FileNodeFilter, String, Appendable) * @see FileNode#getDirContentsFiles(RTC) * @see DirExpectedException#check(FileNode) * @see WritableDirectoryException#check(String) * @see SameSourceAndTargetException#check(FileNode, String) */ public static int copy (FileNode directory, FileNodeFilter filter, String targetDirectory, Appendable a) throws IOException, SameSourceAndTargetException, InvalidPathException, NoSuchFileException { // The purpose of "INTERNAL" here is that we only need to check the input ONCE. DirExpectedException.check(directory); WritableDirectoryException.check(targetDirectory); SameSourceAndTargetException.check(directory, targetDirectory); if (! targetDirectory.endsWith(File.separator)) targetDirectory = targetDirectory + File.separator; return copyINTERNAL(directory, filter, targetDirectory, a); } //Internal Method. Skips Retesting Input Validity, during recursion. private static int copyINTERNAL (FileNode directory, FileNodeFilter filter, String targetDirectory, Appendable a) throws IOException { int count = 0; Iterator<FileNode> iter = directory.getDirContentsFiles(RTC.ITERATOR()); while (iter.hasNext()) { FileNode fn = iter.next(); if ((filter != null) && (! filter.test(fn))) continue; copyFileINTERNAL(fn.getFullPathName(), targetDirectory + fn.name); if (a != null) a.append( BCYAN + "COPY: " + RESET + fn.getFullPathName() + BCYAN + "\tTO:\t" + RESET + targetDirectory + fn.name + '\n' ); count++; } return count; } /** * Copies an entire directory tree to a target-directory. Note, this class will use the * {@code java.io.File.mkdirs()} method to create any sub-directories that exists in the * Source-Directory Tree, but not in the Target-Directory Tree. * * @param directory This is the source or "root node" of the directory-tree that needs to be * (recursively) copied to the {@code 'targetDirectory'}. This {@code FileNode} must be a * directory, or else an {@code DirExpectedException} will be thrown. This parameter may not * be null. * * @param fileFilter If the programmer using this method would like to maintain some control * in deciding which files are copied - copying some, but not others - to the destination / * target-directory, the provide a Java {@code Predicate} which makes decisions on which files * to copy to the target-directory, and which files to leave out of the copy process. * * <BR /><BR /><B><SPAN STYLE="color: red;">FILTER PREDICATE BEHAVIOR:</SPAN></B> This filter * {@code Predicate<FileNode>} will return {@code TRUE} to indicate that the file in question * should be copied, and {@code FALSE} if no copy is needed. * * <BR /><BR /><B>NOTE:</B> This parameter may be null, and if it is it shall just be ignored. * This is the default case, and <I>all files found in each-and-every-level of the source * directory tree will be copied</I> to the target-directory. * * @param dirFilter If the programmer using this method would like to skip <I>entire branches * of the source directory tree</I>, then implement a java predicate that identifies which * sub-directories (read: 'branches') of the source directory-tree should be skipped. This * parameter (a {@code java.util.function.Predicate<FileNode>}) shall receive file-system * directories (not files!) as input to its {@code public boolean test()} method, and if this * method returns {@code FALSE}, the branch that was passed to the {@code Predicate} shall be * skipped entirely by this copy-routine. * * <BR /><BR /><B><SPAN STYLE="color: red;">FILTER PREDICATE BEHAVIOR:</SPAN></B> This filter * {@code Predicate<FileNode>} will return {@code TRUE} to indicate that the sub-directory in * question should be <I>traversed <B>and</B> copied,</I> and {@code FALSE} in order to * <I><B>skip</B> the provided sub-directory entirely</I> from the copy process. * * <BR /><BR /><B>NOTE:</B> If this parameter is null, it shall just be ignored. This is the * default setting, and when this parameter is null, all branches (all sub-directories) of the * {@code FileNode} parameter {@code 'fn'} shall be copied to {@code 'targetDirectory'.} * * <BR /><BR /><B><SPAN STYLE="color: red;">SUBTLE NOTE:</B></SPAN> The following two examples * will hopefully clarify an issue about filters. The parameter {@code 'fileFilter'} is, in * most cases, more useable than the {@code 'dirFilter'} parameter. The {@code 'dirFilter'} * will force the code <B>skip</B> an entire branch of the directory tree without traversing * it. See this example below where the programmer is attempting to copy all files/classes in * the {@code javadoc/Torello/HTML/NodeSearch/} directory that have the word 'TagNode' * * <DIV CLASS="EXAMPLE-SCROLL">{@code * // These lines will load the "javadoc" documentation files for this jar into a FileNode Tree. * // These are mostly the '.html' files for the code-documentation you are reading right now. * FileNode fn = FileNode * .createRoot("javadoc/") * .loadTree(); * * // THIS WILL FAIL to copy the "TagNode" files in the "NodeSearch" directory to 'temp/' * FileTransfer.copyRecursive( * fn, * f -> f.toString().contains("TagNode"), // Expecting any file having "TagNode" in it's name * f -> f.toString().contains("NodeSearch"), // Supposedly expecting directories having "NodeSearch" in their name * "temp/", System.out * ); * // FAILS TO COPY ANY FILES: The directory predicate BLOCKED the first sub-directory from loading! * * // THIS WILL SUCCEED * FileTransfer.copyRecursive( * fn, * f -> StrCmpr.containsAND(f.toString(), "TagNode", "NodeSearch"), * null, * "temp/", System.out * ); * // This SUCCEEDS since the f.toString() method will return the FULL PATH NAME of any file. * // File's having "TagNode" or "NodeSearch" in their file name, or sub-directory path will result * // in the file predicate returning TRUE. 16 Files here will be copied to 'temp/' * // NOTE: The files are javadoc/Torello/HTML/NodeSearch/TagNodeFind.html, and others... * }</DIV> * * @param targetDirectory Where the files shall be copied. This must be a valid directory as * well, or else a {@code FileNotFoundException} shall throw. This method <B>will not</B> * create this directory if it does not exist. See method {@code java.io.File.mkdirs()} for * information on how to create files on the file-system. * * <BR /><BR /><B>NOTE:</B> It is expected that the last character in this {@code String} * contain a directory-separator character (on UNIX, this is the forward-slash ({@code '/'}) * and in MS-DOS, Windows this is the back-slash ({@code '\'}). If this character is not * present, if this {@code String} does not 'end-with' a {@code java.io.File.separator} then * one will be appended to the end of this {@code String}. * * @param a This parameter may be null, but if it is not, then debugging / logging / * informational messages will be sent to this output. * * @return This method makes calls to the single-level, single-directory-version of the * {@code copy(...)} method in this class for each directory found in the tree. This method * shall sum-up all and count all the files as they are copied. The value returned by this * method is an integer specified how many files were copied in the process. * * @throws DirExpectedException If you pass a "file" instance of {@code class FileNode} to * parameter {@code 'directory.'} * * @throws WritableDirectoryException If the initial target-directory, itself, is not available * to Java for copying, then this exception shall throw. In actuality, all sub-directories * that need to be created will be created by this recursive-copy operation - except for the * highest-level "top directory" (the one indicated by the parameter {@code 'targetDirectory'} * - because if that doesn't exist, then this {@code 'WritableDirectoryException'} will throw). * * @throws java.nio.file.NoSuchFileException This will be thrown if the logic which checks to * ensure that the source and target directories are not identical is unable to identify the * <I><B>real path name</B></I> of either the source or target directory. One such possible * situation where this would happen would be if the user applied the UNIX <B>tilda * ({@code '~'})</B> in either the {@code source} or {@code target} directory-name. * * @throws java.nio.file.InvalidPathException This will be thrown if {@code class * java.nio.file.Paths} is unable to instantiate a {@code java.nio.file.Path} for either the * source-directory (parameter {@code directory}), or the {@code targetDirectory}. * * @throws SameSourceAndTargetException This will be thrown if the source and target * directories are found to point to identical locations on the file-system. * * @throws IOException For any IO filesystem errors. * * @see #copy(FileNode, FileNodeFilter, String, Appendable) * @see FileNode#getDirContentsDirs(RTC) * @see DirExpectedException#check(FileNode) * @see WritableDirectoryException#check(String) * @see SameSourceAndTargetException#check(FileNode, String) */ public static int copyRecursive( FileNode directory, FileNodeFilter fileFilter, FileNodeFilter dirFilter, String targetDirectory, Appendable a ) throws IOException, SameSourceAndTargetException, InvalidPathException, NoSuchFileException { // The purpose of "INTERNAL" here is that we only need to check the input ONCE. DirExpectedException.check(directory); WritableDirectoryException.check(targetDirectory); SameSourceAndTargetException.check(directory, targetDirectory); if (! targetDirectory.endsWith(File.separator)) targetDirectory = targetDirectory + File.separator; return copyRecursiveINTERNAL(directory, fileFilter, dirFilter, targetDirectory, a); } // Internal Method. Skips Retesting Input Validity, during recursion. private static int copyRecursiveINTERNAL( FileNode directory, FileNodeFilter fileFilter, FileNodeFilter dirFilter, String targetDirectory, Appendable a ) throws IOException { int numCopied = copyINTERNAL(directory, fileFilter, targetDirectory, a); if (a != null) a.append( "Copied " + StringParse.zeroPad(numCopied) + " files from:" + BRED + " [" + directory.getFullPathName() + "]" + RESET + " to: " + BRED + "[" + targetDirectory + "]" + RESET + '\n' ); Iterator<FileNode> dirs = directory.getDirContentsDirs(RTC.ITERATOR()); while (dirs.hasNext()) { FileNode dir = dirs.next(); if ((dirFilter != null) && (! dirFilter.test(dir))) continue; String newTargetDirectory = targetDirectory + dir.name + File.separator; new File(newTargetDirectory).mkdirs(); numCopied += copyRecursiveINTERNAL(dir, fileFilter, dirFilter, newTargetDirectory, a); } return numCopied; } /** * This method will delete files (not sub-directories) from a source directory. This method is * not recursive, and will not delete files from sub-directories. Files in all other * directories of the directory tree that begins with parameter {@code FileNode 'directory'} * shall all be left-alone, except the files inside the contents of parameter * {@code FileNode 'directory'} itself. * * @param directory This is the source or "root node" of the directory-tree that needs to be * (recursively) copied to the {@code targetDirectory.} This {@code FileNode} must be a * directory, or else a {@code DirExpectedException} will be thrown. This parameter may not be * null. * * @param filter If the programmer using this method would like to maintain some control in * deciding which files are deleted - deleting some, but not others - from {@code 'directory'}, * then he / she should provide a {@code java.util.function.Predicate<FileNode>} here using the * {@code 'filter'} parameter which makes decisions on which files to delete, and which to * leave alone. * * <BR /><BR /><B><SPAN STYLE="color: red;">FILTER PREDICATE BEHAVIOR:</SPAN></B> This filter * {@code Predicate<FileNode>} will return {@code TRUE} to indicate that the file in question * should be deleted, and {@code FALSE} if no delete is needed. * * <BR /><BR /><B>NOTE:</B> This parameter may be null, and if it is it shall just be ignored, * <I>and every file found inside parameter {@code 'directory'} will be removed from the * file-system.</I> * * @param a This parameter may be null, but if it is not, then debugging / logging / * informational messages will be sent to this output. * <EMBED CLASS='external-html' DATA-FILE-ID=APPENDABLE> * * @return An integer that reports how many files were deleted from the file-system. * <BR /><BR /><B><SPAN STYLE="color: red;">NOTE:</B></SPAN> Only files will be deleted by this * method, no directories shall be removed. Also, the only files that are deleted will be the * ones <I>directly found, which are direct-descendants of parameter * {@code FileNode 'directory'}</I> This method is not recursive, and the directory tree will * not be traversed. * * @throws DirExpectedException If you pass a "file" instance of {@code class FileNode} to * parameter {@code 'directory'}. * * @throws IOException For any IO file-system errors. * * @see #deleteFilesRecursive(FileNode, FileNodeFilter, FileNodeFilter, Appendable) * @see FileNode#getDirContentsFiles(RTC) * @see FileNode#getJavaIOFile() * @see DirExpectedException#check(FileNode) */ public static int deleteFiles(FileNode directory, FileNodeFilter filter, Appendable a) throws IOException { // The purpose of "INTERNAL" here is that we only need to check the input ONCE. DirExpectedException.check(directory); return deleteFilesINTERNAL(directory, filter, a); } // Internal Method. Skips Retesting Input Validity, during recursion. private static int deleteFilesINTERNAL(FileNode directory, FileNodeFilter filter, Appendable a) throws IOException { int count = 0; Iterator<FileNode> iter = directory.getDirContentsFiles(RTC.ITERATOR()); while (iter.hasNext()) { FileNode fn = iter.next(); if ((filter != null) && (! filter.test(fn))) continue; File f = fn.getJavaIOFile(); f.delete(); if (a != null) a.append("DELETED: " + BCYAN + fn.getFullPathName() + RESET + '\n'); count++; } return count; } /** * Deletes files sub-directories from a {@code FileNode}. * * <BR /><BR /><B CLASS=JDDescLabel>Deletion Behavior:</B> * * <BR />When, after a delete, a directory or sub-directory is not empty because the * User-Provided Filters requested to skip the deletion of some of the sub-diretories or files, * this method will therefore be unable to remove these sub-directory branches from the * File-System. * * <BR /><BR />This behavior is largely consistent with standard UNIX and MS-DOS commands such * as {@code 'cp', 'mv', 'copy'} etc... Under these Operating-Systems, non-empty directories * cannot be deleted until their contents have been removed completely. * * <BR /><BR /><B CLASS=JDDescLabel>Appendable Log:</B> * * <BR />If a non-null {@code Appendable} (log) is passed to this method, notices are provided * to the user as directories are removed. This may be of use for later reviewing what was * deleted, and what was retained. * * @param directory This is the source or "root node" of the directory-tree that needs to be * (recursively) deleted. This parameter may not be null. This {@code FileNode} must be a * directory, or else a {@code DirExpectedException} will be thrown. * * @param fileFilter If the programmer using this method would like to maintain some control * in deciding which files are deleted, then he/she must provide a Java * {@code java.util.function.Predicate<FileNode>} which makes these decisions regarding which * files to remove, and which files to leave alone. * * <BR /><BR /><B><SPAN STYLE="color: red;">FILTER PREDICATE BEHAVIOR:</SPAN></B> This filter * {@code Predicate<FileNode>} will return {@code TRUE} to indicate that the file in question * should be deleted, and {@code FALSE} if no delete is needed. * * <BR /><BR /><B>NOTE:</B> This parameter may be null, and if it is it shall just be ignored. * This is the default case, and <I>all files found in each-and-every-level of the source * directory tree will be deleted.</I> * * @param dirFilter If the programmer using this method would like to skip <I>entire branches * of the source directory tree</I>, then implement a java predicate that identifies which * sub-directories (read: 'branches') of the source directory-tree should be skipped. This * parameter (a {@code java.util.function.Predicate<FileNode>}) shall receive file-system * directories (not files!) as input to its {@code public boolean test()} method, and if this * method returns {@code FALSE}, the branch that was passed to the {@code Predicate} shall be * skipped entirely by this delete-routine. * * <BR /><BR /><B><SPAN STYLE="color: red;">FILTER PREDICATE BEHAVIOR:</SPAN></B> This filter * {@code Predicate<FileNode>} will return {@code TRUE} to indicate that the sub-directory in * question should be <I>traversed <B>and</B> deleted,</I> and {@code FALSE} in order to * <I><B>skip</B> the provided sub-directory entirely</I> from the delete process. * * <BR /><BR /><B>NOTE:</B> If this parameter is null, it shall just be ignored. This is the * default case, and when this parameter is null, all branches (all sub-directories) of the * {@code FileNode} parameter {@code 'fn'} shall be put through the deletion process. * * @param a This parameter may be null, but if it is not, then debugging / logging / * informational messages will be sent to this output. * * @return This method will return an integer that reports how many files were deleted. It * might be important to note that when sub-directories are deleted, they are only deleted * because they were empty. Any non-empty sub-directory will be left alone, and not removed. * Also, when files are deleted, they add to the "total delete count" which is the output * integer from this method. However, when directories are deleted, their deletion does not * contribute to the output-count. * * @throws DirExpectedException If you pass a "file" instance of {@code class FileNode} to * parameter {@code 'directory'} * * @throws IOException For any IO file-system errors. * * @see #deleteFiles(FileNode, FileNodeFilter, Appendable) * @see FileNode#getDirContentsDirs(RTC) * @see FileNode#getJavaIOFile() * @see DirExpectedException#check(FileNode) */ public static int deleteFilesRecursive( FileNode directory, FileNodeFilter fileFilter, FileNodeFilter dirFilter, Appendable a ) throws IOException { // The purpose of "INTERNAL" here is that we only need to check the input ONCE. DirExpectedException.check(directory); return deleteFilesRecursiveINTERNAL(directory, fileFilter, dirFilter, a); } // Internal Method. Skips Retesting Input Validity, during recursion. private static int deleteFilesRecursiveINTERNAL( FileNode directory, FileNodeFilter fileFilter, FileNodeFilter dirFilter, Appendable a ) throws IOException { int numDeleted = deleteFilesINTERNAL(directory, fileFilter, a); if (a != null) a.append( "Deleted (" + StringParse.zeroPad(numDeleted) + ") files from:" + BRED + " [" + directory.getFullPathName() + "]" + RESET + '\n' ); Iterator<FileNode> dirs = directory.getDirContentsDirs(RTC.ITERATOR()); while (dirs.hasNext()) { FileNode dir = dirs.next(); if ((dirFilter != null) && (! dirFilter.test(dir))) continue; numDeleted += deleteFilesRecursiveINTERNAL(dir, fileFilter, dirFilter, a); } File d = directory.getJavaIOFile(); int numRemainingFiles = d.list().length; boolean shouldDelete = (dirFilter == null) || dirFilter.test(directory); if ((numRemainingFiles == 0) && shouldDelete) { d.delete(); if (a != null) a.append ("Deleted (Empty) Directory: " + directory.getFullPathName() + '\n'); } else if ((a != null) && (numRemainingFiles > 0) && shouldDelete) a.append( "Unable to delete NON-EMPTY Directory: " + directory.getFullPathName() + ", " + numRemainingFiles + " file(s) or dir(s) still remain.\n" ); return numDeleted; } /** * Moves the contents of one directory to another. Avoids moving files that do not pass the * {@code 'filter'} test. If a log parameter ({@code 'a'}) is provided, textual * status-updates will be printed to that log. * * <BR /><BR /><B CLASS=JDDescLabel>Method Heuristic</B> * * <BR />All this method does is to perform, sequentially: * * <BR /><BR /><OL CLASS=JDOL> * <LI>A copy operation of a file to a new directory.</LI> * <LI>A delete operation on the file from the original location.</LI> * </OL> * * @param directory This must be a "directory" not a "file" instance of * {@code public class FileNode} or an exception shall be thrown. If this class is a * directory, then every file that is currently in this directory shall be copied to the * {@code 'targetDirectory'} - and then deleted from this directory. This parameter may not * be null. * * @param targetDirectory Where the files shall be moved. This must be a valid directory as * well, or else a {@code FileNotFoundException} shall throw. This method <B>will not</B> * create this directory if it does not exist. See method {@code java.io.File.mkdirs()} for * information on how to create files on the file-system. * * <BR /><BR /><B>NOTE:</B> It is expected that the last character in this {@code String} * contain a directory-separator character (on UNIX, this is the forward-slash ({@code '/'}) * and in MS-DOS, Windows this is the back-slash ({@code '\'}). If this character is not * present, if this {@code String} does not 'end-with' a {@code java.io.File.separator} then * one will be appended to the end of this {@code String}. * * @param filter This parameter may be null, but if it is not, each file will be tested by this * java-lambda for identifying whether or not it meets the "accept" or "reject" interface * before moving is performed. * * <BR /><BR /><B><SPAN STYLE="color: red;">FILTER PREDICATE BEHAVIOR:</SPAN></B> This filter * {@code Predicate<FileNode>} will return {@code TRUE} to indicate that the file in question * should be moved, and {@code FALSE} if no move is needed. * * @param a This parameter may be null, but if it is not, then debugging / logging / * informational messages will be sent to this output. * <EMBED CLASS='external-html' DATA-FILE-ID=APPENDABLE> * * @return The number of files that were moved. * * @throws DirExpectedException If you pass a "file" instance of {@code class FileNode} to * parameter {@code 'directory.'} * * @throws WritableDirectoryException If the target-directory is not available to Java for * moving. * * @throws java.nio.file.NoSuchFileException This will be thrown if the logic which checks to * ensure that the source and target directories are not identical is unable to identify the * <I><B>real path name</B></I> of either the source or target directory. One such possible * situation where this would happen would be if the user applied the UNIX <B>tilda * ({@code '~'})</B> in either the {@code source} or {@code target} directory-name. * * <BR /><BR />This check is crucial since when performing a {@code MOVE} operation, the * contents of a directory are <B><I>first copied</I></B>, and <B><I>then deleted</B></I>. If * the source and target directories are identical, then after the initial {@code copy} * operation, the logic would simply {@code delete} the original files. * * @throws java.nio.file.InvalidPathException This will be thrown if {@code class * java.nio.file.Paths} is unable to instantiate a {@code java.nio.file.Path} for either the * source-directory (parameter {@code directory}), or the {@code targetDirectory}. * * @throws SameSourceAndTargetException This will be thrown if the source and target * directories are found to point to identical locations on the file-system. Since this is a * {@code MOVE} operation, when moving files, the logic first copies the files and then deletes * the originals. If the source and target directories are identical, after the initial * {@code COPY} operation completes, the logic would simple erase those originals - <I>which * would destroy both copies!</I> * * @throws IOException For any IO file-system errors. * * @see #moveRecursive(FileNode, FileNodeFilter, FileNodeFilter, String, Appendable) * @see DirExpectedException#check(FileNode) * @see WritableDirectoryException#check(String) * @see SameSourceAndTargetException#check(FileNode, String) */ public static int move (FileNode directory, FileNodeFilter filter, String targetDirectory, Appendable a) throws IOException, SameSourceAndTargetException, InvalidPathException, NoSuchFileException { // The purpose of "INTERNAL" here is that we only need to check the input ONCE. DirExpectedException.check(directory); WritableDirectoryException.check(targetDirectory); SameSourceAndTargetException.check(directory, targetDirectory); if (! targetDirectory.endsWith(File.separator)) targetDirectory = targetDirectory + File.separator; return moveINTERNAL(directory, filter, targetDirectory, a); } // Internal Method. Skips Retesting Input Validity, during recursion. private static int moveINTERNAL (FileNode directory, FileNodeFilter filter, String targetDirectory, Appendable a) throws IOException { int count = 0; Iterator<FileNode> iter = directory.getDirContentsFiles(RTC.ITERATOR()); while (iter.hasNext()) { FileNode fn = iter.next(); if ((filter != null) && (! filter.test(fn))) continue; copyFileINTERNAL(fn.getFullPathName(), targetDirectory + fn.name); if (a != null) a.append( BCYAN + "COPY: " + RESET + fn.getFullPathName() + BCYAN + "\tTO:\t" + RESET + targetDirectory + fn.name + '\n' ); fn.getJavaIOFile().delete(); if (a != null) a.append(BCYAN + "DELETE: " + RESET + fn.getFullPathName() + '\n'); count++; } return count; } /** * Copies an entire directory tree to a target-directory, and the removes the original files * & directories from their original location. Note, this class will use the * {@code java.io.File.mkdirs()'} method to create any sub-directories which are present in the * source-directory-tree but not are not present in the target-directory-tree. * * <BR /><BR /><B CLASS=JDDescLabel>Move Behavior:</B> * * <BR />When, after a move, a sub-directory is not be completely empty because the filters * have elected not to skip moving some of files or sub-directories, then this method be will * be unable to remove the old-copies of those directory-branches of the file-system tree. * * <BR /><BR />This behavior is largely consistent with standard UNIX and MS-DOS commands such * as {@code 'cp', 'mv', 'copy'} etc... Under these Operating-Systems, non-empty directories * cannot be deleted until their contents have been removed completely. * * <BR /><BR /><B CLASS=JDDescLabel>Appendable Log:</B> * * <BR />If a non-null {@code Appendable} (log) is passed to this method, notices are provided * to the user as directories are removed. This may be of use for later reviewing what was * deleted, and what was retained. * * @param directory This is the source or "root node" of the directory-tree that needs to be * (recursively) copied to the {@code 'targetDirectory'}. This {@code FileNode} must be a * directory, or else an {@code DirExpectedException} will be thrown. This parameter may not * be null. * * @param targetDirectory Where the files shall be moved. This must be a valid directory as * well, or else a {@code FileNotFoundException} shall throw. This method <B>will not</B> * create this directory if it does not exist. See method {@code java.io.File.mkdirs()} for * information on how to create files on the file-system. * * <BR /><BR /><B>NOTE:</B> It is expected that the last character in this {@code String} * contain a directory-separator character (on UNIX, this is the forward-slash ({@code '/'}) * and in MS-DOS, Windows this is the back-slash ({@code '\'}). If this character is not * present, if this {@code String} does not 'end-with' a {@code java.io.File.separator} then * one will be appended to the end of this {@code String}. * * @param fileFilter If the programmer using this method would like to maintain some control * in deciding which files are copied - copying some, but not others - to the destination / * target-directory, the provide a Java {@code java.util.function.Predicate<FileNode>} which * makes decisions on which files to copy to {@code 'targetDirectory'}, and which files to * leave out of the copy process. * * <BR /><BR /><B><SPAN STYLE="color: red;">FILTER PREDICATE BEHAVIOR:</SPAN></B> This filter * {@code Predicate<FileNode>} will return {@code TRUE} to indicate that the file in question * should be moved, and {@code FALSE} if no move is needed. * * <BR /><BR /><B>NOTE:</B> This parameter may be null, and if it is it shall just be ignored. * This is the default case, and <I>all files found in each-and-every-level of the source * directory tree will be copied</I> to the {@code targetDirectory}. * * @param dirFilter If the programmer using this method would like to skip <I>entire branches * of the source directory tree</I>, then implement a java predicate that identifies which * sub-directories (read: 'branches') of the source directory-tree should be skipped. * This parameter (a {@code java.util.function.Predicate<FileNode>}) shall receive file-system * directories (not files!) as input to its {@code public boolean test()} method, and if this * method returns {@code FALSE}, the branch that was passed to the {@code Predicate} shall be * skipped entirely by this move-routine. * * <BR /><BR /><B><SPAN STYLE="color: red;">FILTER PREDICATE BEHAVIOR:</SPAN></B> This filter * {@code Predicate<FileNode>} will return {@code TRUE} to indicate that the sub-directory in * question should be <I>traversed <B>and</B> moved</I>, and {@code FALSE} in order to * <I><B>skip</B> the provided sub-directory entirely</I> from the move process. * * <BR /><BR /><B>NOTE:</B> If this parameter is null, it shall just be ignored. This is the * default case, and when this parameter is null, all branches (all sub-directories) of the * {@code FileNode} parameter {@code 'fn'} shall be copied to the target directory. * * @param a This parameter may be null, but if it is not, then debugging / logging / * informational messages will be sent to this output. * * @return This method makes calls to the single-level, single-directory-version of the * {@code 'copy(...)'} method in this class for each directory found in the tree. This method * shall sum-up all and count all the files as they are copied. The value returned by this * method is an integer specified how many files were copied in the process. * * @throws DirExpectedException If you pass a "file" instance of {@code class FileNode} to * parameter {@code 'directory.'} * * @throws WritableDirectoryException If the initial target-directory, itself, is not available * to Java for copying, then this exception shall throw. In actuality, all sub-directories * that need to be created will be created by this recursive-copy operation - except for the * highest-level "top directory" (the one indicated by the parameter {@code 'targetDirectory'} - * because if that doesn't exist, then a {@code 'WritableDirectoryException'} will throw). * * @throws java.nio.file.NoSuchFileException This will be thrown if the logic which checks to * ensure that the source and target directories are not identical is unable to identify the * <I><B>real path name</B></I> of either the source or target directory. One such possible * situation where this would happen would be if the user applied the UNIX <B>tilda * ({@code '~'})</B> in either the {@code source} or {@code target} directory-name. * * <BR /><BR />This check is crucial since when performing a {@code MOVE} operation, the * contents of a directory are <B><I>first copied</I></B>, and <B><I>then deleted</B></I>. If * the source and target directories are identical, then after the initial {@code copy} * operation, the logic would simply {@code delete} the original files. * * @throws java.nio.file.InvalidPathException This will be thrown if {@code class * java.nio.file.Paths} is unable to instantiate a {@code java.nio.file.Path} for either the * source-directory (parameter {@code directory}), or the {@code targetDirectory}. * * @throws SameSourceAndTargetException This will be thrown if the source and target * directories are found to point to identical locations on the file-system. Since this is a * {@code MOVE} operation, when moving files, the logic first copies the files and then deletes * the originals. If the source and target directories are identical, after the initial * {@code COPY} operation completes, the logic would simple erase those originals - <I>which * would destroy both copies!</I> * * @throws IOException For any IO filesystem errors. * * @see #move(FileNode, FileNodeFilter, String, Appendable) * @see FileNode#getDirContentsDirs(RTC) * @see DirExpectedException#check(FileNode) * @see WritableDirectoryException#check(String) * @see SameSourceAndTargetException#check(FileNode, String) */ public static int moveRecursive( FileNode directory, FileNodeFilter fileFilter, FileNodeFilter dirFilter, String targetDirectory, Appendable a ) throws IOException, SameSourceAndTargetException, InvalidPathException, NoSuchFileException { // The purpose of "INTERNAL" here is that we only need to check the input ONCE. DirExpectedException.check(directory); WritableDirectoryException.check(targetDirectory); SameSourceAndTargetException.check(directory, targetDirectory); if (! targetDirectory.endsWith(File.separator)) targetDirectory = targetDirectory + File.separator; return moveRecursiveINTERNAL(directory, fileFilter, dirFilter, targetDirectory, a); } // Internal Method. Skips Retesting Input Validity, during recursion. private static int moveRecursiveINTERNAL ( FileNode directory, FileNodeFilter fileFilter, FileNodeFilter dirFilter, String targetDirectory, Appendable a ) throws IOException { int numMoved = moveINTERNAL(directory, fileFilter, targetDirectory, a); if (a != null) a.append( "Moved " + StringParse.zeroPad(numMoved) + " files from:" + BRED + " [" + directory.getFullPathName() + "]" + RESET + " to: " + BRED + "[" + targetDirectory + "]" + RESET + '\n' ); Iterator<FileNode> dirs = directory.getDirContentsDirs(RTC.ITERATOR()); while (dirs.hasNext()) { FileNode dir = dirs.next(); if ((dirFilter != null) && (! dirFilter.test(dir))) continue; String newTargetDirectory = targetDirectory + dir.name + File.separator; new File(newTargetDirectory).mkdirs(); numMoved += moveRecursiveINTERNAL(dir, fileFilter, dirFilter, newTargetDirectory, a); } File d = directory.getJavaIOFile(); int numRemainingFiles = d.list().length; boolean shouldDelete = (dirFilter == null) || dirFilter.test(directory); if ((numRemainingFiles == 0) && shouldDelete) { d.delete(); if (a != null) a.append("Deleted (Empty) Directory: " + directory.getFullPathName() + '\n'); } else if ((a != null) && (numRemainingFiles > 0) && shouldDelete) a.append( "Unable to delete NON-EMPTY Directory: " + directory.getFullPathName() + ", " + numRemainingFiles + " file(s) or dir(s) still remain.\n" ); return numMoved; } private static void copyFileINTERNAL(String inFileName, String outFileOrDirName) throws IOException { try ( FileInputStream fis = new FileInputStream(inFileName); FileOutputStream fos = new FileOutputStream(outFileOrDirName); ) { byte[] b = new byte[5000]; int result = 0; while ((result = fis.read(b)) != -1) fos.write(b, 0, result); fos.flush(); } } } |