1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 | package Torello.Java; import java.io.*; import java.util.*; import java.util.zip.*; import java.util.stream.*; import java.nio.file.*; import java.lang.reflect.InvocationTargetException; import Torello.Java.Additional.*; import Torello.JavaDoc.StaticFunctional; import Torello.JavaDoc.Excuse; /** * Operating-System independent File Read & Write utilities that reduce many common Java * File I/O Commands to a single method invocation, focusing heavily on Java's Serialization * feature. * * <EMBED CLASS='external-html' DATA-FILE-ID=FILE_RW> */ @StaticFunctional(Excused="TRUNCATE_EOF_CHARS", Excuses=Excuse.FLAG) public class FileRW { private FileRW() { } /** * This is used by method {@link #loadFileToString(String)}. By default this flag is set to * {@code TRUE}, and when it is, any trailing {@code EOF chars, ASCII-0} found in a file that * is to be interpreted as a Text-File, will be truncated from the {@code String} returned by * that {@code 'reader'} method. */ public static boolean TRUNCATE_EOF_CHARS = true; // ******************************************************************************************** // ******************************************************************************************** // writeFile // ******************************************************************************************** // ******************************************************************************************** /** * Writes the entire contents of a single {@code java.lang.String} to a file on the File-System * named {@code 'fName'}. * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_WRITABLE_DIR> * * @param s A {@code java.lang.String} which is appended, in entirety, to the file ('fName') * * @param fName The name of the file to which the contents of the {@code java.lang.String} * are appended. If This file doesn't already exist, it is created here. * * @throws IOException If any I/O errors have occurred with the File-System / disk. */ public static void writeFile(CharSequence s, String fName) throws IOException { File outF = new File(fName); outF.createNewFile(); // This writer is 'java.lang.AutoCloseable'. // // NOTE: The IOException will still be thrown out of this method if it occurs. It is not // caught! try (FileWriter fw = new FileWriter(outF)) { fw.write(s.toString()); } } /** * This takes an {@code Iterable<String>}, and a filename, and writes each * {@code java.lang.String} in the {@code Iterator} that it produces to the file * specified by File-Name parameter {@code 'fName'} * * <BR /><BR /><B CLASS=JDDescLabel>New-Line Characters:</B> * * <BR />A newline {@code ('\n')} is appended to the end of each {@code java.lang.String} * before writing it to the file. * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_WRITABLE_DIR> * * @param i This is any java {@code Iterable<String>} object. Each of these will be written, * in succession, to the file named by parameter {@code 'fName'} * * @param fName The name of the file to which the contents of the {@code java.lang.String} * are appended. If This file doesn't already exist, it is created here. * * @throws IOException If an I/O error has occurred as a result of the File-System or * disk operation. */ public static void writeFile(Iterable<String> i, String fName) throws IOException { Iterator<String> iter = i.iterator(); File outF = new File(fName); outF.createNewFile(); // This writer is 'java.lang.AutoCloseable'. // // NOTE: The IOException will still be thrown out of this method if it occurs. It is not // caught! try (FileWriter fw = new FileWriter(outF)) { while (iter.hasNext()) fw.write(iter.next() + "\n"); } } // ******************************************************************************************** // ******************************************************************************************** // writeFile_NO_NEWLINE // ******************************************************************************************** // ******************************************************************************************** /** * This takes an {@code Iterable} of String, and a filename and writes each * {@code java.lang.String} in the {@code Iterator} that it produces to the file specified by * File-Name parameter {@code 'fName'} * * <BR /><BR /><B CLASS=JDDescLabel>New-Line Characters:</B> * * <BR />In this function a newline {@code ('\n')} character <I>is <B>not</B> appended</I> to * the end of each {@code java.lang.String} of the input {@code Iterator}. * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_WRITABLE_DIR> * * @param i This is any java {@code 'Iterable'} object that can iterate {@code 'String'}. * Each of these will be written, in succession, to the file named by {@code 'fName'} * * @param fName The name of the file to which the contents of the {@code java.lang.String} * are appended. If This file doesn't already exist, it is created here. * * @throws IOException If an I/O error has occurred as a result of the File-System or disk * operation. */ public static void writeFile_NO_NEWLINE(Iterable<String> i, String fName) throws IOException { Iterator<String> iter = i.iterator(); File outF = new File(fName); outF.createNewFile(); // This Writer is 'java.lang.AutoCloseable'. // // NOTE: The IOException will still be thrown out of this method if it occurs. It is not // caught! try (FileWriter fw = new FileWriter(outF)) { while (iter.hasNext()) fw.write(iter.next()); } } // ******************************************************************************************** // ******************************************************************************************** // appendToFile // ******************************************************************************************** // ******************************************************************************************** /** * Appends the entire input {@code java.lang.String} - actually a * {@code java.lang.CharSequence} to the file on the File-System named {@code 'fName'} * * <BR /><BR /><B CLASS=JDDescLabel>Directory Requirements:</B> * * <BR />Though the file does not need to exist already in order for this file to be written * the directory hierarchy needs to exist, or a java {@code 'IOException'} will occur. * * @param s A {@code java.lang.CharSequence} (almost identical to {@code 'String'}) which is * appended, in entirety, to the File-Name parameter {@code 'fName'} * * @param fName The name of the file to which the contents of the {@code java.lang.String} are * appended. If This file doesn't already exist, it is created here. * * @throws IOException If an I/O error has occurred as a result of the File-System or * disk operation. */ public static void appendToFile(CharSequence s, String fName) throws IOException { File f = new File(fName); if (! f.exists()) f.createNewFile(); Files.write(Paths.get(fName), s.toString().getBytes(), StandardOpenOption.APPEND); } /** * This takes an {@code Iterable<String>}, and a filename, and appends each * {@code java.lang.String} in the {@code Iterator} that it produces to the file * specified by File-Name parameter {@code 'fName'} * * <BR /><BR /><B CLASS=JDDescLabel>Directory Requirements:</B> * * <BR />Though the file does not need to exist already in order for this file to be written * the directory hierarchy needs to exist, or a java {@code 'IOException'} will occur. * * @param i This is any java {@code Iterable<String>} object. Each of these will be written, * in succession, to the file named by parameter {@code 'fName'} * * @param fName The name of the file to which the contents of the {@code java.lang.String} * are appended. If This file doesn't already exist, it is created here. * * @param addNewLines When this parameter is passed {@code TRUE}, a New-Line character will be * appended after each {@code String} that is written. When {@code FALSE}, only the * {@code String's} produced by the {@code Iterable}, themselves, are appended to the file. * * @throws IOException If an I/O error has occurred as a result of the File-System or * disk operation. */ public static void appendToFile(Iterable<String> i, String fName, boolean addNewLines) throws IOException { File f = new File(fName); if (! f.exists()) f.createNewFile(); // Uses the "Ternary Operator" / "Conditional Operator" Syntax, but it's a little hard to // read that. There is a '?' and a ':' after the boolean 'addNewsLines' Iterable<String> passedIterable = addNewLines // If the user has requested to add newlines, wrap the passed Iterable inside of a new // Iterable that appends a new-line character to the output of the User's 'next()' // method (which is just returning the String's to be written to disk - less the newline) ? new Iterable<>() { private final Iterator<String> iterInternal = i.iterator(); // Funny Note: All an "Iterable" is is an Object that returns an Iterator. The // interface "Iterable" only has one non-Default Method - iterator(). Re-Write // that method to return a slightly altered Iterator<String> public Iterator<String> iterator() { return new Iterator<String>() { public boolean hasNext() { return iterInternal.hasNext(); } public String next() { return iterInternal.next() + '\n'; } }; } } // Otherwise, just assign the Users Iterable to the "passedIterable" Variable : i; // Now write the Passed Iterable of String, using java.nio.file.Files Files.write(Paths.get(fName), passedIterable, StandardOpenOption.APPEND); } // ******************************************************************************************** // ******************************************************************************************** // Load File (as String's} // ******************************************************************************************** // ******************************************************************************************** /** * This will load the entire contents of a Text-File on disk to a single * {@code java.lang.String} * * <BR /><BR /><B CLASS=JDDescLabel>Trailing Zeros:</B> * * <BR />Some of the ugliest code to see is that which finds {@code 'EOF'} characters liberally * inserted into a simple Text-File. When reading a file (which, regardless of whether it * <I>actually is a Text-File</I>), this method will remove any <I>trailing {@code ASCII-0}</I> * characters (literally, {@code char c == 0}) from the files that are read. * * <BR /><BR />Finding {@code '.html'} or {@code '.java'} files in which some editor (for * whatever reason) has inserted {@code EOF-like} characters to the end of the text can make * programming a headache. * * <BR /><BR />Suffice it to say, the {@code String} that is returned from this method will * contain the last non-zero character (including CRLF, {@code '\n'} or {@code '\r'} * character that was read from the file. Operating-systems do not require that a file have a * trailing zero to interpret them. * * <BR /><BR />Character {@code '0'} is a legacy / older-version of the EOF Marker. * {@code '.java'}-Files certainly don't need them, and they can actually be a problem when a * developer is checking for file's that have equal-{@code String's} in them. * * <BR /><BR /><B CLASS=JDDescLabel>Static Boolean-Flag</B> * * <BR />This class (class {@code FileRW}) has a {@code static, boolean} flag that is able to * prevent / shunt this 'Trailing Zero Removing' behavior. When {@link #TRUNCATE_EOF_CHARS} is * set to {@code FALSE}, reading a file into a {@code String} using this method will return the * {@code String} - <I>including as many Trailing Zero-Characters as have been appended to the * end of that file</I>. * * @param fName the File-Name of a valid Text-File in the File-System * * @return The entire contents of the file as a {@code String}. * * @throws IOException If an I/O error has occurred as a result of the File-System or * disk operation. */ public static String loadFileToString(String fName) throws IOException { // The reader is 'java.lang.AutoCloseable'. // // NOTE: The IOException will still be thrown out of this method if it occurs. It is not // caught! try (FileReader fr = new FileReader(fName)) { int len = (int) new File(fName).length(); char[] cArr = new char[len]; int offset = 0; int charsRead = 0; int charsRemaining = len; while ((offset < len) && ((charsRead = fr.read(cArr, offset, charsRemaining)) != -1)) { offset += charsRead; charsRemaining -= charsRead; } len = cArr.length; if (TRUNCATE_EOF_CHARS) while ((len > 0) && (cArr[len-1] == 0)) len--; return (len != cArr.length) ? new String(cArr, 0, len) : new String(cArr); } } /** * Convenience Method. * <BR />Invokes: {@link #loadFileToStream(String, boolean)} * <BR />Converts: {@code Stream<String>} into {@code String[]} */ public static String[] loadFileToStringArray(String fName, boolean includeNewLine) throws IOException { return loadFileToStream(fName, includeNewLine).toArray(String[]::new); } /** * This will load a file to a Java {@code Stream} instance. * * @param fName A File-Name of a valid Text-File in the File-System. * * @param includeNewLine if this is {@code TRUE}, a {@code '\n'} (newline/CRLF) is appended to * the end of each {@code java.lang.String} read from this file. If not, the original newline * characters which occur in the file, will be eliminated. * * <BR /><BR /><B><SPAN STYLE="color: red;">MINOR NOTE:</SPAN></B> This method will make one * (potentially minor) mistake. If the final character in the input-file is, itself, a * new-line (if the file ends with a {@code 'CRLF' / 'CR'}), then this method should return a * {@code Stream<String>} that is identical to the original file. However, <I>if the final * character in the file <B>is not</B> a new-line {@code '\n'}</I>, then the * {@code Stream<String>} that is returned will have an extra new-line appended to the last * {@code String} in the {@code Stream}, and the resultant {@code Stream<String>} will * be longer than the original file by 1 character. * * @return The entire contents of the file as a series of {@code java.lang.String} contained by * a {@code java.util.stream.Stream<String>}. Converting Java {@code Stream's} to other data * container types is as follows: * * <EMBED CLASS='external-html' DATA-FILE-ID=STRMCNVT> * * @throws IOException If an I/O error has occurred as a result of the File-System or disk * operation. */ public static Stream<String> loadFileToStream(String fName, boolean includeNewLine) throws IOException { // These readers's are 'java.lang.AutoCloseable'. // // NOTE: The IOException will still be thrown out of this method if it occurs. It is not // caught! // // ALSO: In try-with-resources blocks, if there is a problem/exception, these // classes are all (automatically) closed/flushed, in reverse order. try ( FileReader fr = new FileReader(fName); BufferedReader br = new BufferedReader(fr); ) { Stream.Builder<String> b = Stream.builder(); String s = ""; if (includeNewLine) while ((s = br.readLine()) != null) b.add(s + "\n"); else while ((s = br.readLine()) != null) b.add(s); return b.build(); } } /** * Convenience Method. * <BR />Invokes: {@link #loadFileToCollection(Collection, String, boolean)} * <BR />Passes: Newly instantiated {@code Vector<String>} to {@code 'collectionChoice'} */ public static Vector<String> loadFileToVector(String fName, boolean includeNewLine) throws IOException { return loadFileToCollection(new Vector<String>(), fName, includeNewLine); } /** * This method loads the contents of a file to a {@code java.util.Collection<String>} object, * where each {@code java.lang.String} in the output / returned {@code Collection} is a * different "line of text" from the input-file. This is identical to invoking: * * <DIV CLASS=LOC>{@code * Collection<String> myTextFile = FileRW.loadFileToString("someFile.txt"0.split('\n') * }</DIV> * * <BR /><B CLASS=JDDescLabel>Variable-Type Parameter:</B> * * <BR />This method uses Java's Variable-Type Parameter syntax to allow the programmer * to decide what type of {@code Collection<String>} they would like returned from this method. * Common examples would include {@code Vector<String>, ArrayList<String>, HashSet<String>} * etc. * * <BR /><BR /><B CLASS=JDDescLabel>Loading EOF:</B> * * <BR />This method will make one small mistake. If the final character inside the input-file * is, itself, a new-line, then this method will return a Java {@code String-Collection} which * is is identical to the original file. * * <BR /><BR />However, <I>if the final character in the file <B>is not</B> a new-line * {@code '\n'} character</I>, then the returned {@code Collection} will have an extra new-line * appended immediately after the last {@code String} in the {@code Collection}. Furthermore, * the resultant {@code Collection<String>} will be longer than the original file by 1 character. * * @param collectionChoice This must be an instance of a class that extends Java's * base {@code class Collection<String>} - <I>using {@code 'String'} as the generic-type * parameter.</I> It will be populated with the lines from a Text-File using the * {@code Collection.add(String)} method. * * @param <T> This may be any class which extends {@code java.util.Collection}. It is * specified as a "Type Parameter" because this collection is returned as a result of this * function. Perhaps it is superfluous to return the same reference that is provided by the * user as input to this method, but this certainly doesn't change the method signature or * make it more complicated. * * @param fName the File-Name of a valid Text-File on the File-System. * * @param includeNewLine if this is {@code TRUE}, a {@code '\n'} (newline/CRLF) is appended to * the end of each {@code java.lang.String} read from this file. If not, the original newline * characters which occur in the file, will be eliminated. * * @return An identical reference to the reference passed to parameter * {@code 'collectionChoice'} * * @throws IOException If an I/O error has occurred as a result of the File-System or disk * operation. */ public static <T extends Collection<String>> T loadFileToCollection (T collectionChoice, String fName, boolean includeNewLine) throws IOException { // These readers's are 'java.lang.AutoCloseable'. // // NOTE: The IOException will still be thrown out of this method if it occurs. It is not // caught! // // ALSO: In try-with-resources blocks, if there is a problem/exception, these // classes are all (automatically) closed/flushed, in reverse order. try ( FileReader fr = new FileReader(fName); BufferedReader br = new BufferedReader(fr); ) { String s = ""; if (includeNewLine) while ((s = br.readLine()) != null) collectionChoice.add(s + "\n"); else while ((s = br.readLine()) != null) collectionChoice.add(s); } return collectionChoice; } // ******************************************************************************************** // ******************************************************************************************** // Write ONE Object To File // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #writeObjectToFile(Object, String, boolean)} * <BR />Catches Exception */ public static boolean writeObjectToFileNOCNFE(Object o, String fName, boolean ZIP) throws IOException { try { writeObjectToFile(o, fName, ZIP); return true; } catch (ClassNotFoundException cnfe) { return false; } } /** * Writes a {@code java.lang.Object} to a file for storage, and future reference. * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_WRITABLE_DIR> * * @param o An {@code Object} to be written to a file as a <I><B>"Serializable"</B></I> * {@code java.lang.Object} * * @param fName The name of the output file * * @param ZIP a boolean that, when {@code TRUE}, will cause the object's data to be compressed * before being written to the output file. * * @throws IOException If an I/O error has occurred as a result of the File-System or disk * operation. * * @throws ClassNotFoundException This exception is thrown when the Java Virtual * Machine (JVM) tries to load a particular class and the specified class cannot be found in * the classpath. */ public static void writeObjectToFile(Object o, String fName, boolean ZIP) throws IOException, ClassNotFoundException { // These stream's are 'java.lang.AutoCloseable'. // // NOTE: The IOException and ClassNotFoundException will still be thrown out of this // method if they occur. They are not caught! // // ALSO: In try-with-resources blocks, if there is a problem/exception, these // classes are all (automatically) closed/flushed, in reverse order. if (ZIP) try ( FileOutputStream fos = new FileOutputStream(fName); GZIPOutputStream gzip = new GZIPOutputStream(fos); ObjectOutputStream oos = new ObjectOutputStream(gzip); ) { oos.writeObject(o); } else try ( FileOutputStream fos = new FileOutputStream(fName); ObjectOutputStream oos = new ObjectOutputStream(fos); ) { oos.writeObject(o); } } // ******************************************************************************************** // ******************************************************************************************** // Write ALL Objects ToFile // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #writeAllObjectsToFile(Iterable, String, boolean)} * <BR />Catches Exception */ public static boolean writeAllObjectsToFileNOCNFE(Iterable<?> i, String fName, boolean ZIP) throws IOException { try { writeAllObjectsToFile(i, fName, ZIP); return true; } catch (ClassNotFoundException cnfe) { return false; } } /** * Writes a series of {@code java.lang.Object} to a file for storage, and future reference. * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_WRITABLE_DIR> * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_1OBJ_FILE> * * @param i A series, {@code Collection}, or {@code List} of {@code Object's} to be written * to a file in <I><B>Serializable</B></I> format. * * @param fName The name of the output file * * @param ZIP a {@code boolean} that, when {@code TRUE}, will cause the {@code Object's} * data to be compressed before being written to the output-file. * * @throws IOException If an I/O error has occurred as a result of the File-System or * disk operation. * * @throws ClassNotFoundException This exception is thrown when the Java Virtual * Machine (JVM) tries to load a particular class and the specified class cannot be found in * the {@code CLASSPATH}. */ public static void writeAllObjectsToFile(Iterable<?> i, String fName, boolean ZIP) throws IOException, ClassNotFoundException { Iterator<?> iter = i.iterator(); // These stream's are 'java.lang.AutoCloseable'. // // NOTE: The IOException and ClassNotFoundException will still be thrown out of this // method if they occur. They are not caught! // // ALSO: In try-with-resources blocks, if there is a problem/exception, these // classes are all (automatically) closed/flushed, in reverse order. if (ZIP) try ( FileOutputStream fos = new FileOutputStream(fName); GZIPOutputStream gzip = new GZIPOutputStream(fos); ObjectOutputStream oos = new ObjectOutputStream(gzip); ) { while (iter.hasNext()) oos.writeObject(iter.next()); } else try ( FileOutputStream fos = new FileOutputStream(fName); ObjectOutputStream oos = new ObjectOutputStream(fos); ) { while (iter.hasNext()) oos.writeObject(iter.next()); } } // ******************************************************************************************** // ******************************************************************************************** // read ONE Object From File // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #readObjectFromFile(String, boolean)} * <BR />Catches Exception */ public static Object readObjectFromFileNOCNFE(String fName, boolean ZIP) throws IOException { try { return readObjectFromFile(fName, ZIP); } catch (ClassNotFoundException cnfe) { return null; } } /** * Reads an {@code Object} from a Data-File which must contain a serialized * {@code java.lang.Object}. * * <DIV CLASS="EXAMPLE">{@code * // Create some Object for writing to the File-System, using Object Serialization * int[] dataArr = some_data_method(); * * // It is always easier to pass 'true' to the compression boolean parameter * FileRW.writeObjectToFile(dataArr, "data/myDataFile.dat", true); * * ... * * // Later on, this file may be read back into the program, using this call: * Object o = FileRW.readObjectFromFile("data/myDataFile.dat", true); * * // This check prevents compiler-time warnings. The Annotation "SuppressWarnings" * // would also work. * dataArr = (o instanceof int[]) ? (int[]) o : null; * }</DIV> * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_1OBJ_FILE> * * @param fName The name of a Data-File that contains a serialized {@code java.lang.Object} * * @param ZIP if this is {@code TRUE}, it is assumed that the Data-File contains a * Zip-Compressed {@code Object} * * @return The {@code Object} that was written to the Data-File. * * @throws IOException If an I/O error has occurred as a result of the File-System or * disk operation. * * @throws ClassNotFoundException This exception is thrown when the Java Virtual * Machine (JVM) tries to load a particular class and the specified class cannot be found * in the {@code CLASSPATH}. */ public static Object readObjectFromFile(String fName, boolean ZIP) throws IOException, ClassNotFoundException { // These stream's are 'java.lang.AutoCloseable'. // // NOTE: The IOException and ClassNotFoundException will still be thrown out of this // method if they occur. They are not caught! // // ALSO: In try-with-resources blocks, if there is a problem/exception, these // classes are all (automatically) closed/flushed, in reverse order. try ( FileInputStream fis = new FileInputStream(fName); ObjectInputStream ois = ZIP ? new ObjectInputStream(new GZIPInputStream(fis)) : new ObjectInputStream(fis); ) { return ois.readObject(); } } /** * Convenience Method. * <BR />Invokes: {@link #readObjectFromFile(String, Class, boolean)} * <BR />Catches Exception */ public static <T> T readObjectFromFileNOCNFE(String fName, Class<T> c, boolean ZIP) throws IOException { try { return readObjectFromFile(fName, c, ZIP); } catch (ClassNotFoundException cnfe) { return null; } } /** * Reads an {@code Object} from a Data-File which must contain a serialized * {@code java.lang.Object}. * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_1OBJ_FILE> * * @param fName The name of a Data-File that contains a serialized {@code java.lang.Object} * * @param c This is the type of the {@code Object} expecting to be read from disk. A value * for this parameter can always be obtained by referencing the {@code static} field * {@code '.class'} which is attached to <I>every object</I> in java. * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_CLASS_T> * * @param <T> This should be set to the return type of this method. By passing the expecred * return-type class, you may conveniently avoid having to cast the returned instance, or worry * about suppressing compiler warnings. * * @param ZIP if this is {@code TRUE}, it is assumed that the Data-File contains a * Zip-Compressed {@code Object} * * @return The {@code Object} that was read from the Data-File. * * @throws IOException If an I/O error has occurred as a result of the File-System or disk * operation. * * @throws ClassNotFoundException This exception is thrown when the Java Virtual * Machine (JVM) tries to load a particular class and the specified class cannot be found in * the {@code CLASSPATH}. */ public static <T> T readObjectFromFile(String fName, Class<T> c, boolean ZIP) throws IOException, ClassNotFoundException { Object o = readObjectFromFile(fName, ZIP); if (o == null) return null; if (c.isInstance(o)) return c.cast(o); throw new ClassNotFoundException( "Although an object was indeed read from the file you have named [" + fName + "], " + "that object was not an instance of [" + c.getName() + "], " + "but rather of [" + o.getClass().getName() + "]" ); } // ******************************************************************************************** // ******************************************************************************************** // read ALL OBJECTS FromFile // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #readAllObjects(Class, Collection, String, boolean)} * <BR />Passes: {@code Object.class} to {@code 'objType'} * <BR />Passes: Newly instantiated {@code Vector<Object>} to {@code 'collection'} */ public static Vector<Object> readAllObjectsToVector(String fName, boolean ZIP) throws IOException, ClassNotFoundException { return readAllObjects(Object.class, new Vector<Object>(), fName, ZIP); } /** * Convenience Method. * <BR />Invokes: {@link #readAllObjects(Class, Collection, String, boolean)} * <BR />Passes: Newly instantiated {@code Vector<T>} to {@code 'collection'} */ public static <T> Vector<T> readAllObjectsToVector(Class<T> objType, String fName, boolean ZIP) throws IOException, ClassNotFoundException { return readAllObjects(objType, new Vector<T>(), fName, ZIP); } /** * Reads all {@code Object's} found inside a Data-File. This Data-File should contain only * java-serialized {@code java.lang.Object's}. * * @param objType <EMBED CLASS='external-html' DATA-FILE-ID=FRW_OBJTYPE_PARAM> * * @param <T> This allows the programmer to inform this method what type of {@code Object's} * are stored in the Serialized Object File, specified by {@code 'fName'}. * * @param collection This should be the desired {@code Collection<E>} that the programmer * would like be populated with the instances of type {@code 'objType'} read from file * {@code 'fName'}. Variable-Type parameter {@code 'E'} needs to be equal-to or an * ancestor of {@code 'objType'} * * @param <U> Merely for convenience, this method returns the {@code Collection} instance that * is passed (by parameter {@code 'Collection'}) as a result of this function. Therefore, the * Type Parameter {@code 'U'} identifies the Return Type of this method. * * @param fName The name of a Data-File that contains serialized {@code Object's} * * @param ZIP if this is {@code TRUE}, it is assumed that the Data-File contains Zip-Compressed * objects * * @return A reference to the {@code Collection} that was passed to this method. * * @throws IOException If an I/O error has occurred as a result of the File-System or disk * operation. */ public static <T, U extends Collection<T>> U readAllObjects (Class<T> objType, U collection, String fName, boolean ZIP) throws IOException, ClassNotFoundException { // Temporary Variable, used in both versions of this method Object o; // These stream's are 'java.lang.AutoCloseable'. // // NOTE: The IOException and ClassNotFoundException will still be thrown out of this // method if they occur. They are not caught! // // ALSO: In try-with-resources blocks, if there is a problem/exception, these // classes are all (automatically) closed/flushed, in reverse order. if (ZIP) try ( FileInputStream fis = new FileInputStream(fName); GZIPInputStream gis = new GZIPInputStream(fis); ObjectInputStream ois = new ObjectInputStream(gis); ) { while ((o = ois.readObject()) != null) if (objType.isInstance(o)) collection.add(objType.cast(o)); else throw new ClassNotFoundException( "At least one of the objects in the serialized object file " + "[" + fName + "], " + "was not an instance of [" + objType.getName() + "], " + "but rather [" + o.getClass().getName() + "]" ); } catch (EOFException eofe) { } else try ( FileInputStream fis = new FileInputStream(fName); ObjectInputStream ois = new ObjectInputStream(fis); ) { while ((o = ois.readObject()) != null) if (objType.isInstance(o)) collection.add(objType.cast(o)); else throw new ClassNotFoundException( "At least one of the objects in the serialized object file " + "[" + fName + "], " + "was not an instance of [" + objType.getName() + "], " + "but rather [" + o.getClass().getName() + "]" ); } catch (EOFException eofe) { } return collection; } /** * Convenience Method. * <BR />Invokes: {@link #readAllObjectsToStream(Class, String, boolean)} * <BR />Passes: {@code Object.class} to {@code 'objType'} */ public static Stream<Object> readAllObjectsToStream(String fName, boolean ZIP) throws IOException, ClassNotFoundException { return readAllObjectsToStream(Object.class, fName, ZIP); } /** * Reads all objects found inside a Data-File. This Data-File should contain only * java-serialized {@code Object's}. * * @param fName The name of a Data-File that contains the serialized {@code Object's} * * @param objType This is the type of the {@code Object's} expecting to be read from disk. A * value for this parameter can always be obtained by referencing the static field * {@code '.class'} which is attached to <I>every {@code Object}</I> in Java. For instance, to * read a Data-File containing a series of {@code Date} instances, use {@code Date.class} as the * value to pass to this parameter. * * @param <T> This parameter informs this method what type of Serialized Objects are saved * within {@code 'fName'}. The Java {@code Stream} that is returned as a result of this method * will have the type {@code Stream<T>}. * * @param ZIP if this is {@code TRUE}, it is assumed that the Data-File contains Zip-Compressed * {@code Object's} * * @return A {@code Stream<T>} of all {@code Object's} found in the Data-File. Converting * Java {@code Stream's} to other Data-Container types is as follows: * * <EMBED CLASS='external-html' DATA-FILE-ID=STREAM_CONVERT_T> * * @throws IOException If an I/O error has occurred as a result of the File-System or disk * operation. * * @throws ClassNotFoundException This exception is thrown when the Java Virtual * Machine (JVM) tries to load a particular class and the specified class cannot be found in * the classpath. */ public static <T> Stream<T> readAllObjectsToStream(Class<T> objType, String fName, boolean ZIP) throws IOException, ClassNotFoundException { Stream.Builder<T> b = Stream.builder(); Object o = null; FileInputStream fis = new FileInputStream(fName); ObjectInputStream ois = ZIP ? new ObjectInputStream(new GZIPInputStream(fis)) : new ObjectInputStream(fis); try { while ((o = ois.readObject()) != null) if (objType.isInstance(o)) b.accept(objType.cast(o)); else throw new ClassNotFoundException( "At least one of the objects in the serialized object file [" + fName + "], " + "was not an instance of [" + objType.getName() + "], " + "but rather [" + o.getClass().getName() + "]" ); } catch (EOFException eofe) { } finally { fis.close(); } return b.build(); } // ******************************************************************************************** // ******************************************************************************************** // Base-64 Read / Write Stuff (Text File) // ******************************************************************************************** // ******************************************************************************************** /** * Uses Java's {@code Object} serialization mechanism to serialize a {@code java.lang.Object}, * and then uses the {@code Base64 String-MIME Encoding} system, also provided by java, to * convert the {@code Object} into a text-safe {@code java.lang.String} that may be viewed, * e-mailed, written to a web-page, etc. * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_1OBJ_FILE> * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_EXAMPLE_01> * * @param o This may be any serializable {@code java.lang.Object} instance. It will be written * to a Text-File after first serializing the {@code Object}, and then next converting the * serialized data-bits to MIME-safe encoded text. * * @param fileName The fileName that will be used to save this {@code Object} as a Text-File. */ public static void writeObjectToTextFile(Object o, String fileName) throws IOException { FileRW.writeFile(StringParse.objToB64MimeStr(o), fileName); } /** * This will read a java serialized, and MIME-Converted, MIME-Safe {@code java.lang.String} * from a text file and return the {@code Object} that it represented * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_1OBJ_FILE> * * @param fileName The name of the file containing the MIME-Encoded Serialized * {@code java.lang.Object}. * * @return The {@code Object} that had been encoded into the Text-File. */ public static Object readObjectFromTextFile(String fileName) throws IOException { return StringParse.b64MimeStrToObj(loadFileToString(fileName)); } /** * Convenience Method. * <BR />Invokes: {@link #readObjectFromTextFile(String, Class)} * <BR />Catches Exception */ public static <T> T readObjectFromTextFileNOCNFE(String fileName, Class<T> c) throws IOException { try { return readObjectFromTextFile(fileName, c); } catch (ClassNotFoundException cnfe) { return null; } } /** * This will read a java serialized, and MIME-Converted, MIME-Safe {@code java.lang.String} * from a text file and return the {@code Object} that it represented * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_1OBJ_FILE> * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_EXAMPLE_01> * * @param fileName The name of the file containing the MIME-Encoded Serialized * {@code java.lang.Object}. * * @param c This is the type of the {@code Object} expecting to be read from disk. A value * for this parameter can always be obtained by referencing the {@code static} field * {@code '.class'}, which is attached to <I>every {@code Object}</I> in java. * * <EMBED CLASS='external-html' DATA-FILE-ID=FRW_CLASS_T> * * @param <T> This Type Parameter informs this method what type of Base-64 Serialized Object * is saved within Text File {@code 'fileName'}. The returned result of this method will have * this type, for convenience to avoid casting the {@code Object} (<I>unless that * {@code Object} is a Java Generic, and you wish to avoid a "Raw Types" warning</I>. See * further details inside the explanation about parameter {@code 'c'}). * * @return The {@code Object} that had been encoded into the Text-File. * * @throws IOException If an I/O error has occurred as a result of the File-System or disk * operation. * * @throws ClassNotFoundException This exception is thrown when the Java Virtual * Machine (JVM) tries to load a particular class and the specified class cannot be found in * the {@code CLASSPATH}. */ public static <T> T readObjectFromTextFile(String fileName, Class<T> c) throws IOException, ClassNotFoundException { Object o = StringParse.b64MimeStrToObj(loadFileToString(fileName)); if (o == null) return null; if (c.isInstance(o)) return c.cast(o); throw new ClassNotFoundException( "Although an object was indeed read from the file you have named [" + fileName + "], " + "that object was not an instance of [" + c.getName() + "], " + "but rather of [" + o.getClass().getName() + "]" ); } // ******************************************************************************************** // ******************************************************************************************** // Object Input & Object Output Streams // ******************************************************************************************** // ******************************************************************************************** /** * Creates a simple {@code ObjectInputStream} - usually if multiple {@code Object's} have been * written to a single file. It was better practice to put {@code Object's} in a * {@code java.util.Vector}, and write one {@code java.util.Vector} during serialization. * * <BR /><BR />This, eventually, can became inadequate when downloading large numbers of HTML * results, where the need to write a large Data-File (intermittently - by saving intermediate * results) is needed. * * @param fName This is the File-Name of the Data-File where the serialized {@code Object's} * have been stored. * * @param ZIP If this is set to {@code TRUE}, the data will be de-compressed. * * @return A java {@code ObjectInputStream} * * @throws IOException If an I/O error has occurred as a result of the File-System * or disk operation. */ public static ObjectInputStream getOIS(String fName, boolean ZIP) throws IOException { return ZIP ? new ObjectInputStream(new GZIPInputStream(new FileInputStream(new File(fName)))) : new ObjectInputStream(new FileInputStream(new File(fName))); } /** * Creates a simple {@code ObjectOutputStream} - usually if multiple {@code Object's} need * to be written to a single file. It was better practice to put {@code Object's} in a * {@code java.util.Vector}, and write one {@code java.util.Vector} during serialization. * * @param fName This is the File-Name of the Data-File where the serialized {@code Object's} * will be stored. * * @param ZIP If this is set to {@code TRUE}, the data will be compressed. * * @return A java {@code ObjectInputStream} * * @throws IOException If an I/O error has occurred as a result of the File-System or * disk operation. */ public static ObjectOutputStream getOOS(String fName, boolean ZIP) throws IOException { return ZIP ? new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(new File(fName)))) : new ObjectOutputStream(new FileOutputStream(new File(fName))); } // ******************************************************************************************** // ******************************************************************************************** // Copy, Move, Delete // ******************************************************************************************** // ******************************************************************************************** /** * This method will perform a byte-for-byte copy of a file from one location to another. * * @param inFileName The name of the input-file. It will be byte-for-byte copied to an output * File-Name. * * @param outFileOrDirName The name of the output-file, or the name of the directory where the * file shall be moved. * * <BR /><BR />If this file already exists <I>and it is a file (not a directory)</I> * it will be over-written. * * <BR /><BR />If parameter {@code 'outFileOrDirName'} names a directory - <I>due * to having an ending {@code File.separator}</I>, <B>but</B> does not appear to name a * directory that exists, this method will throw a {@code FileNotFoundException}. * * <BR /><BR />This can be avoided, however, by passing {@code TRUE} to parameter * {@code 'createDirsIfNotExist'}. If {@code 'outFileOrDirName'} specifies a directory (by * virtue of the fact that it ends with the {@code File.separator String}) - <I>and * {@code 'createDirsIfNotExist'} is {@code TRUE}</I>, then this method will first create any * and all sub-directories needed using the standard Java's {@code File.mkdirs()} method before * copying the file. * * <BR /><BR /><B><SPAN STYLE="color: red;">SUMMARY:</SPAN></B> The programmer may provide * either a Directory-Name or a File-Name to parameter {@code 'outFileOrDirName'}. If a * Directory-Name was provided, the moved file will <I>keep its name</I> - having the same name * as the original file, ({@code 'inFileName'}) had (but have been copied to directory * {@code 'outFileOrDirName'}). * * <BR /><BR /><B><SPAN STYLE="color: red;">BEHAVIOR NOTE:</SPAN></B> The behavior of this * copy operation is generally / mostly the same as the standard {@code UNIX} or {@code MS-DOS} * commands {@code 'cp'} and {@code 'copy'} (respectively) - <I>differing only in this method's * ability to have directories created using {@code File.mkdirs()}</I> * * @param createDirsIfNotExist If the target output-file is situated in a directory-path that * does not exist, this method will throw an exception. However, if this boolean parameter is * set to {@code TRUE} and the aforementioned situation occurs where the complete-directory * tree does not exist, then this method will first attempt to create the directories using * {@code java.io.File.mkdirs().} * * @throws SecurityException If boolean parameter {@code 'createDirsIfNotExist'} is * {@code TRUE} <I>and if</I> the directory named by parameter {@code 'outFileName'} does not * exist, <I>and if</I> attempting to create such a directory is not permitted by the * Operating-System, then this exception shall throw. * * @throws IOException For any number of fail-causes in reading or writing input stream data. * An explanation of all causes of such an operation is beyond the scope of this * method-documentation entry. * * @throws FileNotFoundException If the {@code 'inFileName'} is not found, or * {@code 'outFileOrDirName'} uses a directory path that doesn't exist on the File-System, * <B>and</B> parameter {@code 'createDirsIfNotExist'} is set to {@code FALSE}. * * @throws SameSourceAndTargetException This exception will be thrown if the <CODE>Java Virtual * Machine</CODE> ascertains that the source and target locations point to the same physical * disk locations. The classes utilized for this operation are from package * {@code java.nio.file.*}; * * @throws InvalidPathException If the <I>Java Virtual Machine</I> is unable to instantiate an * instance of {@code java.nio.files.Path} for either the {@code 'inFileName'} parameter or the * {@code 'outFileOrDirName'}, then this exception will be thrown. * * @throws NoSuchFileException If, after instantiating an instance of {@code Path} for either * the {@code source} or the {@code target} locations, the <I>Java Virtual Machine</I> is * unable to build an instance of {@code Path} using the method {@code Path.toRealPath()}, then * this exception will throw. */ public static void copyFile (String inFileName, String outFileOrDirName, boolean createDirsIfNotExist) throws IOException { File f = new File(outFileOrDirName); if (createDirsIfNotExist) if (! f.exists()) f.mkdirs(); if (f.isDirectory()) { if (! outFileOrDirName.endsWith(File.separator)) outFileOrDirName = outFileOrDirName + File.separator; outFileOrDirName = outFileOrDirName + StringParse.fromLastFileSeparatorPos(inFileName); } String inPath = Paths.get(inFileName).toRealPath().toString(); // throws InvalidPathException // throws NoSuchFileException try { if (Paths.get(outFileOrDirName).toRealPath().toString().equals(inPath)) throw new SameSourceAndTargetException( "The Source File Name and the Target Location provided to your copyFile " + "request operation appear to point to the same physical-disk location:\n" + inPath ); } catch (NoSuchFileException e) { } // NOTE: Mostly (but not always) the output file won't exist yet... If it does not, // then we really don't need to worry about over-writing the origina file. // REMEMBER: The only purpose of the above test is to make sure that the source and // target are not the same (to avoid clobbering the original file) FileInputStream fis = new FileInputStream(inFileName); FileOutputStream fos = new FileOutputStream(outFileOrDirName); byte[] b = new byte[5000]; int result = 0; try { while ((result = fis.read(b)) != -1) fos.write(b, 0, result); } finally { fis.close(); fos.flush(); fos.close(); } } /** * Convenience Method. * <BR />Invokes: {@code java.io.File.delete()} */ public static void deleteFiles(String... fileNames) { for (String fileName : fileNames) (new File(fileName)).delete(); } /** * Convenience Method. * <BR />Invokes: {@link #copyFile(String, String, boolean)} * <BR />And-Then: deletes */ public static void moveFile (String inFileName, String outFileName, boolean createDirsIfNotExist) throws IOException { copyFile(inFileName, outFileName, createDirsIfNotExist); (new File(inFileName)).delete(); } /** * This deletes an entire directory, including any sub-directories. It is like the UNIX * switch {@code -r} for the command {@code rm}, or the old Microsoft DOS Command * {@code 'deltree'} for deleting directories. It simply reuses the class {@code FileTransfer} * * <BR /><BR /><B CLASS=JDDescLabel>Platform Independance (WORA):</B> * * <BR />If this method is invoked from a UNIX or LINUX platform, then it will, generally, * bring about identical results as a call to {@link Shell#RM(String, String)} where the UNIX * {@code "-r"} (recursive) flag has been included / set. On such a platform, an entire * directory would be eliminated. * * <BR /><BR />However, if executed from Windows, the class {@link Shell} would fail since it * only works on UNIX, but this method here would still succeed at its task. It is a * "Platform-Independent" function. * * @param directoryName This should be a valid directory on the File-System. * * <BR /><BR /><B><SPAN STYLE="color: red">WARNING:</B></SPAN> This command <B><I>does indeed * delete the entire directory-tree of the named directory!</I></B> * * @param reCreateDirectoryOnExit This parameter allows the user to create an <I>an empty * directory with the same name</I> as the directory that was just deleted, after all of the * directory's contents have been deleted. When this parameter is passed a value of * {@code TRUE}, the equivalent of the UNIX command {@code mkdir 'directoryName'} will be * executed prior to exiting this method. * * <BR /><BR />This can be a small convenience if the user desired that the directory be * cleared, rather than deleted completely. * * @param log This parameter may be null, and if it is, it will be ignored. This shall receive * textual log output from the deletion process. * * <EMBED CLASS='external-html' DATA-FILE-ID=APPENDABLE> * * @return This shall return a count on the total number of deleted files. Note that when * directories are deleted (not files), their deletion <I>shall not count towards</I> the * total returned in this integer. * * @throws IllegalArgumentException Throws if the {@code String} provided to parameter * {@code directoryName} does not name a valid directory on the File-System. */ public static int delTree (String directoryName, boolean reCreateDirectoryOnExit, Appendable log) throws IOException { if (directoryName == null) throw new NullPointerException ("You have provided null to parameter 'directoryName', but this is not allowed here."); File f = new File(directoryName); if (! f.exists()) throw new IllegalArgumentException( "The directory name you have provided: [" + directoryName + "] was not found on the " + "File System. Aborted." ); if (! f.isDirectory()) throw new IllegalArgumentException( "The value you have provided to parameter 'directoryName' was: " + "[" + directoryName + "], but unfortunately this is not the name of a directory on " + "the File System, but rather a file. This is not allowed here." ); // Uses class FileNode to build the directory into Java Memory. // It is possibly of interest to note, that if running this java code on a UNIX or // LINUX platform, this method should perform the exact same operation as an invocation // of Shell.RM(directoryName, "-r"); FileNode fn = FileNode.createRoot(directoryName).loadTree(); int ret = FileTransfer.deleteFilesRecursive(fn, null, null, log); if (reCreateDirectoryOnExit) f.mkdirs(); return ret; } /** * This may read a Text-File containing integer data. If this data is a <B>Comma Separated * Value</B> {@code 'CSV'} Text-File, please pass {@code TRUE} to the parameter * {@code 'isCSV'}. If this file contains integers that have commas between digits in groups * of three (like {@code '30,000'}) please pass {@code TRUE} to the parameter * {@code 'hasCommasInInts'}. * * <EMBED CLASS='external-html' DATA-TYPE=int DATA-FILE-ID=FRW_READNUM_FFORMAT> * * <BR /><BR /><B CLASS=JDDescLabel>Number-Format:</B> * * <BR />The numbers in this Text-File must be parse-able by Java class * {@code java.lang.Integer} via its method {@code Integer.parseInt(String s, int radix)} * * @param fileName This should contain the File-Name which itself contains a list of integers. * These integers may be separated by either a comma ({@code ','}) or a space ({@code ' '}). * * @param hasCommasInInts It is allowed that the file named by {@code 'fileName'} contain * integers which use the commonly found notation of having a comma between groups of three * digits within an integer. For instance the number {@code '98765'}, to a reader, is often * represented as {@code '98,765'}. When this parameter is set to {@code TRUE}, this method * shall simply remove any comma that is found juxtaposed between two digits before * processing any text found in the file. * * @param isCSV If the text file named by {@code 'fileName'} is a <B>Comma Separated Value</B> * file, then please pass {@code TRUE} to this parameter. If {@code FALSE} is passed here, * then it is mandatory that the individual numbers inside the Text-File are separated by at * least one white-space character. * * <BR /><BR /><B STYLE="color: red">IMPORTANT:</B> If it is decided to set both of the boolean * parameters to {@code TRUE} - <I>where the integers have commas, * <B STYLE="color: red">and</B> the integers are separated by commas</I>, it is up to the * programmer to ensure that the individual numbers, themselves, are <I>not only</I> separated * by a comma, <I>but also</I> separated by a space as well. * * @param radix This is the {@code 'radix'}, which is also usually called the number's * {@code 'base'} that is to be used when parsing the numbers. Since Java's {@code class * java.lang.Integer} is used to perform the parse, <I>both</I> the {@code 'radix'}, <I>and</I> * the data found in the Text-File must conform to the Java method * {@code Integer.parseInt(String s, int radix)}. * * <BR /><BR /><B>NOTE:</B> This parameter may not be ignored. If the numbers in the Text-File * are to be interpreted as standard {@code 'decimal'} (<I>Base 10</I>) numbers, then the user * should simply pass the constant {@code '10'} to this parameter. * * @return This method shall return a {@code java.util.stream.IntStream} consisting of the * integers that were found within the Text-File provided by {@code 'fileName'}. * * <BR /><BR /><B>NOTE:</B> An instance of {@code IntStream} is easily converted to an * {@code int[]} array using the method {@code IntStream.toArray()}. * * @throws FileNotFoundException If the file named by parameter {@code 'fileName'} is not * found or not accessible in the File-System, then this exception will throw. * * @throws IOException This exception throws if there are any errors that occur while * reading this file from the File-System. * * @throws NumberFormatException If any of the numbers read from the Text-File are not * properly formatted, then this exception shall throw. * * @see StringParse#NUMBER_COMMMA_REGEX * @see StringParse#COMMA_REGEX * @see StringParse#WHITE_SPACE_REGEX */ public static IntStream readIntsFromFile (String fileName, boolean hasCommasInInts, boolean isCSV, int radix) throws FileNotFoundException, IOException { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); IntStream.Builder b = IntStream.builder(); String s = ""; while ((s = br.readLine()) != null) { // Skip blank lines. if ((s = s.trim()).length() == 0) continue; // This line simply finds String-Matches that match "Digit,Digit" and replaces // such matches with "DigitDigit". After this replacement, they are parsed with ease. // NOTE: NUMBER_COMMMA_REGEX = Pattern.compile("\\d,\\d"); if (hasCommasInInts) s = StringParse.NUMBER_COMMMA_REGEX.matcher(s).replaceAll("$1$2").trim(); String[] numbers = isCSV ? StringParse.COMMA_REGEX.split(s) : StringParse.WHITE_SPACE_REGEX.split(s); for (String number : numbers) if ((number = number.trim()).length() > 0) b.accept(Integer.parseInt(number, radix)); } br.close(); fr.close(); return b.build(); } /** * This may read a Text-File containing integer data. If this data is a <B>Comma Separated * Value</B> {@code 'CSV'} Text-File, please pass {@code TRUE} to the parameter * {@code 'isCSV'}. If this file contains integers that have commas between digits in groups * of three (like {@code '30,000'}) pleas pass {@code TRUE} to the parameter * {@code 'hasCommasInLongs'}. * * <EMBED CLASS='external-html' DATA-TYPE=long DATA-FILE-ID=FRW_READNUM_FFORMAT> * * <BR /><BR /><B CLASS=JDDescLabel>Number-Format:</B> * * <BR />The numbers in this Text-File must be parse-able by Java class * {@code class java.lang.Long} using the method {@code Long.parseLong(String s, int radix)} * * @param fileName This should contain the File-Name which itself contains a list of * {@code 'long'} integers. These {@code long} integers may be separated by either a comma * ({@code ','}) or a space ({@code ' '}). * * @param hasCommasInLongs It is allowed that the file named by {@code 'fileName'} contain * {@code long}-integers which use the commonly found notation of having a comma between groups * of three digits within a {@code long} integer. For instance the number {@code '98765'}, to * a reader, is often represented as {@code '98,765'}. When this parameter is set to * {@code TRUE}, this method shall simply remove any comma that is found juxtaposed between * two digits before processing any text found in the file. * * @param isCSV If the text file named by {@code 'fileName'} is a <B>Comma Separated Value</B> * file, then please pass {@code TRUE} to this parameter. If {@code FALSE} is passed here, * then it is mandatory that the individual numbers inside the Text-File are separated by at * least one white-space character. * * <BR /><BR /><B STYLE="color: red">IMPORTANT:</B> If it is decided to set both of the boolean * parameters to {@code TRUE} - <I>where the {@code long} integers have commas, * <B STYLE="color: red">and</B> the {@code long} integers are separated by commas</I>, it is * up to the programmer to ensure that the individual numbers, themselves, are <I>not only</I> * separated by a comma, <I>but also</I> separated by a space as well. * * @param radix This is the {@code 'radix'}, which is also usually called the number's * {@code 'base'} that is to be used when parsing the numbers. Since Java's {@code class * Long} is used to perform the parse, <I>both</I> the {@code 'radix'}, <I>and</I> the data * found in the Text-File must conform to the Java method * {@code Long.parseLong(String s, int radix)}. * * <BR /><BR /><B>NOTE:</B> This parameter may not be ignored. If the numbers in the Text-File * are to be interpreted as standard {@code 'decimal'} (<I>Base 10</I>) numbers, then the user * should simply pass the constant {@code '10'} to this parameter. * * @return This method shall return a {@code java.util.stream.LongStream} consisting of the * {@code long}-integers that were found within the Text-File provided by {@code 'fileName'}. * * <BR /><BR /><B>NOTE:</B> An instance of {@code LongStream} is easily converted to a * {@code long[]} array using the method {@code LongStream.toArray()}. * * @throws FileNotFoundException If the file named by parameter {@code 'fileName'} is not * found or not accessible in the File-System, then this exception will throw. * * @throws IOException This exception throws if there are any errors that occur while * reading this file from the File-System. * * @throws NumberFormatException If any of the numbers read from the Text-File are not * properly formatted, then this exception shall throw. * * @see StringParse#NUMBER_COMMMA_REGEX * @see StringParse#COMMA_REGEX * @see StringParse#WHITE_SPACE_REGEX */ public static LongStream readLongsFromFile (String fileName, boolean hasCommasInLongs, boolean isCSV, int radix) throws FileNotFoundException, IOException { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); LongStream.Builder b = LongStream.builder(); String s = ""; while ((s = br.readLine()) != null) { // Skip blank lines. if ((s = s.trim()).length() == 0) continue; // This line simply finds String-Matches that match "Digit,Digit" and replaces // such matches with "DigitDigit". After this replacement, they are parsed with ease. // NOTE: NUMBER_COMMMA_REGEX = Pattern.compile("\\d,\\d"); if (hasCommasInLongs) s = StringParse.NUMBER_COMMMA_REGEX.matcher(s).replaceAll("$1$2").trim(); String[] numbers = isCSV ? StringParse.COMMA_REGEX.split(s) : StringParse.WHITE_SPACE_REGEX.split(s); for (String number : numbers) if ((number = number.trim()).length() > 0) b.accept(Long.parseLong(number, radix)); } br.close(); fr.close(); return b.build(); } /** * This may read a Text-File containing floating-point data. If this data is a <B>Comma * Separated Value</B> {@code 'CSV'} Text-File, please pass {@code TRUE} to the parameter * {@code 'isCSV'}. If this file contains {@code double's} that have commas between digits * in groups of three (like {@code '30,000,000,00'}) pleas pass {@code TRUE} to the parameter * {@code 'hasCommasInDoubles'}. * * <EMBED CLASS='external-html' DATA-TYPE=long DATA-FILE-ID=FRW_READNUM_FFORMAT> * * <BR /><BR /><B CLASS=JDDescLabel>Number-Format:</B> * * <BR />The numbers in this Text-File must be parse-able by Java class * {@code class java.lang.Double} using the method {@code Double.parseDouble(String s)} * * @param fileName This should contain the File-Name which itself contains a list of * {@code 'double'} values. These {@code double's} may be separated by either a comma * ({@code ','}) or a space ({@code ' '}). * * @param hasCommasInDoubles It is allowed that the file named by {@code 'fileName'} contain * {@code double}-values which use the commonly found notation of having a comma between groups * of three digits within a {@code double} value. For instance the number {@code '98765.01'}, * to a reader, can be represented as {@code '98,765.01'}. When this parameter is set to * {@code TRUE}, this method shall simply remove any comma that is found juxtaposed between * two digits before processing any text found in the file. * * @param isCSV If the text file named by {@code 'fileName'} is a <B>Comma Separated Value</B> * file, then please pass {@code TRUE} to this parameter. If {@code FALSE} is passed here, * then it is mandatory that the individual numbers inside the Text-File are separated by at * least one white-space character. * * <BR /><BR /><B STYLE="color: red">IMPORTANT:</B> If it is decided to set both of the boolean * parameters to {@code TRUE} - <I>where the {@code double} values have commas, * <B STYLE="color: red">and</B> the {@code double} values are separated by commas</I>, it is * up to the programmer to ensure that the individual numbers, themselves, are <I>not only</I> * separated by a comma, <I>but also</I> separated by a space as well. * * @return This method shall return a {@code java.util.stream.DoubleStream} consisting of the * {@code double}-values that were found within the Text-File provided by {@code 'fileName'}. * * <BR /><BR /><B>NOTE:</B> An instance of {@code DoubleStream} is easily converted to a * {@code double[]} array using the method {@code DoubleStream.toArray()}. * * @throws FileNotFoundException If the file named by parameter {@code 'fileName'} is not * found or not accessible in the File-System, then this exception will throw. * * @throws IOException This exception throws if there are any errors that occur while * reading this file from the File-System. * * @throws NumberFormatException If any of the numbers read from the Text-File are not * properly formatted, then this exception shall throw. * * @see StringParse#NUMBER_COMMMA_REGEX * @see StringParse#COMMA_REGEX * @see StringParse#WHITE_SPACE_REGEX */ public static DoubleStream readDoublesFromFile (String fileName, boolean hasCommasInDoubles, boolean isCSV) throws FileNotFoundException, IOException { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); DoubleStream.Builder b = DoubleStream.builder(); String s = ""; while ((s = br.readLine()) != null) { // Skip blank lines. if ((s = s.trim()).length() == 0) continue; // This line simply finds String-Matches that match "Digit,Digit" and replaces // such matches with "DigitDigit". After this replacement, they are parsed with ease. // NOTE: NUMBER_COMMMA_REGEX = Pattern.compile("\\d,\\d"); if (hasCommasInDoubles) s = StringParse.NUMBER_COMMMA_REGEX.matcher(s).replaceAll("$1$2").trim(); String[] numbers = isCSV ? StringParse.COMMA_REGEX.split(s) : StringParse.WHITE_SPACE_REGEX.split(s); for (String number : numbers) if ((number = number.trim()).length() > 0) b.accept(Double.parseDouble(number)); } br.close(); fr.close(); return b.build(); } /** * Convenience Method. * <BR />Invokes: {@code java.io.FileOutputStream.write(byte[])}. * <BR /><B>NOTE:</B> This may throw {@code IOException, FileNotFoundException}, etc... */ public static void writeBinary(byte[] bArr, String fileName) throws IOException { // The input-stream is 'java.lang.AutoCloseable'. // // NOTE: The IOException will still be thrown out of this method if it occurs. It is not // caught! This also (potentially) throws SecurityException & FileNotFoundException try (FileOutputStream fos = new FileOutputStream(fileName)) { fos.write(bArr); } } /** * Convenience Method. * <BR />Invokes: {@code java.io.FileOutputStream.write(byte[], int, int)}. * <BR /><B>NOTE:</B> This may throw {@code IOException, IndexOutOfBoundsException}, etc... */ public static void writeBinary(byte[] bArr, int offset, int len, String fileName) throws IOException { // The input-stream is 'java.lang.AutoCloseable'. // // NOTE: The IOException will still be thrown out of this method if it occurs. It is not // caught! This also (potentially) throws SecurityException, FileNotFoundException, // IndexOutOfBoundsExcepton (if 'offset' or 'len' do not adhere to 'bArr' definition) try (FileOutputStream fos = new FileOutputStream(fileName)) { fos.write(bArr, offset, len); } } /** * Convenience Method. * <BR />Invokes: {@link #readBinary(String, int, int)}. */ public static byte[] readBinary(String fileName) throws FileNotFoundException, IOException { return readBinary(fileName, 0, -1); } /** * Reads data from a binary file into a Java {@code byte[]} array. * * <BR /><BR />Unlike Java's {@code FileOutputStream.write(...)} method, the {@code read(...)} * Java provides in that same exact class is more difficult to use. This method is much longer * than its corresponding {@link #writeBinary(byte[], String)} method. * * @param fileName The name of the file (on the File-System) to read. * * @param offset The number of {@code byte's} to skip before appending a {@code byte} into the * output {@code byte[]} array. If the value provided to parameer {@code 'offset'} is longer * than the size of the file itself, then a <B>zero-length {@code byte[]} array</B> will be * returned. * * <BR /><BR /><B STYLE='color: red'>IMPORTANT:</B> The meaning of the value in parameter * {@code 'offset'} is very different from the meaning of a parameter by that exact same name, * except in method {@code read(...)} of class {@code FileInputStream}. <B>HERE</B> the offset * is the number of <I>bytes to skip inside of file {@code 'fileName'}, before saving the values * that are read froom disk.</I> In the {@code FileInputStream}, offset is used as an array * pointer. * * @param len Once the internal-loop has begun copying bytes from the Data-File into the * returned {@code byte[]} array, {@code byte's} will continue to be copied into this array * until precisely {@code 'len'} bytes have been copied. * * <BR /><BR /><B STYLE='color:red'>IMORTANT:</B> The user may provide any negative number to * this parameter, and the read process will simply begin at position {@code 'offset'}, and * continue reading until the End of the File has been reached. * * @return Returns a {@code byte[]}-array, with a length of (parameter) {@code 'len'} bytes. * * @throws FileNotFoundException Class {@code java.io.FileInputStream} will throw a * {@code FileNotFoundException} if that class is passed a {@code 'fileName'} that does not * exist, or is a File-Name that represents a directory not a file. * * @throws SecurityException If a security manager exists and its {@code checkRead} method * denies read access to the file. * * @throws IOException The {@code FileInputStream} instance, and the {@code java.io.File} * instance are both capable of throwing {@code IOException}. * * @throws IllegalArgumentException * * <BR /><BR /><UL CLASS=JDUL> * <LI> The value provided to {@code 'offset'} is negative</LI> * <LI> The value provided to parameter {@code 'len'} is zero.</LI> * </UL> * * @throws FileSizeException This exception throws if any of the following are detected: * * <BR /><BR /><UL CLASS=JDUL> * <LI> The returned {@code byte[]} array cannot have a size larger than * {@code Integer.MAX_VALUE}. If the returned array would have a larger size - <I>based * on any combination of provided input values</I>, then this exception will throw. * </LI> * <LI> The value provided to {@code 'offset'} is larger than the size of the underlying * file that is specified by parameter {@code 'fileName'} * </LI> * <LI> The total of {@code offset + len} is larger than the size of the underlying file. * </LI> * <LI> An invocation of the method {@code File.length()} returns zero, indicating that the * file is either unreadable, non-existant, or possibly empty. * </LI> * </UL> * * @throws EOFException This particular exception should not be expected. Before any reads are * done, the size of the Data-File is first checked to see if it is big enough to have the * amount of data that is requested by input paramters {@code 'offset'} and {@code 'len'}. If * however, an error occurrs, and the Operating System returns an {@code EOF} earlier than * expected (for unforseen reasons), then {@code EOFException} would throw. */ public static byte[] readBinary(String fileName, int offset, int len) throws FileNotFoundException, IOException { // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // EXCEPTION CHECKS // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** if (offset < 0) throw new IllegalArgumentException ("The value of offset (" + offset + ") is negative."); if (len == 0) throw new IllegalArgumentException ("A value of zero was provided to parameter 'len.' This is not allowed"); File f = new File(fileName); try (FileInputStream fis = new FileInputStream(f)) { long fileLen = f.length(); // A file-name that points to a completely empty file was passed to parameter 'fileName' // **OR** the operating system returned 0 for some other error-related reason. // According to the Java-Doc explanation, a '0' returned value might mean there were // errors when trying to access the file. if (fileLen == 0) throw new FileSizeException( "Calling java.io.File.length() returned 0 for the file-name that was " + "provided to this method:\n[" + fileName + "]. This might mean that the file " + "does not exist, or has other issues.", 0 ); // The file would end before we have even started reading bytes - after having skipped // 'offset' nmber of initial bytes. if (offset > fileLen) throw new FileSizeException( "The value of offset (" + offset + ") is larger than the size of the binary " + "file, which only had size (" + fileLen + ").", fileLen ); // If 'len' was passed a negative value, that value is actually meaningless - and was // just used to indicate that reading the entire file starting at byte # 'offset' is // what the user is requesting. if (len > 0) // This simply checks how many bytes the file would need to have to provide for // reading from 'offset' up until 'offset + len' if ((offset + len) > fileLen) throw new FileSizeException( "The file [" + fileName + "] apparently has a size of [" + fileLen + "], " + "but the offset (" + offset + ") and the length (" + len + ") that was " + "requested sum to (" + (offset+len) + "), which is greater than that size.", fileLen ); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // More Exception Checks: Check what the size of the returned byte[] array will be // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Negative-Length means that bytes are read until an EOF occurrs if (len < 0) { long bytesToRead = fileLen - offset; if (bytesToRead > Integer.MAX_VALUE) throw new FileSizeException( "This file has [" + fileLen + "] bytes of data, and even with an offset of " + '[' + offset + "], there are still " + bytesToRead + " bytes of data to " + "place into the array. This value is larger than Integer.MAX_VALUE " + "(" + Integer.MAX_VALUE + ").", fileLen ); else len = (int) bytesToRead; } // A Positive length means that exactly the value inside input-parameter 'len' need to // be placed into the returned byte[] array. else if (len > Integer.MAX_VALUE) throw new FileSizeException( "This file has [" + fileLen + "] bytes of data, which is larger than " + "Integer.MAX_VALUE (" + Integer.MAX_VALUE + ").", fileLen ); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // FIRST, if there is a NON-ZERO OFFSET, then exactly OFFSET bytes must be skipped // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** int failedReads = 0; long bytesSkipped = 0; int totalBytesSkipped = 0; int bytesRemaining = offset; // NOTE: This loop is skipped, immediately / automatically, if indeed 'offset' is zero while (totalBytesSkipped < offset) if ((bytesSkipped = fis.skip(bytesRemaining)) == 0) { if (failedReads++ == 10) throw new IOException( "There have 10 repeated attempts to read the file's data, but all " + "attempts have resulted in empty-reads with zero bytes being retrieved " + "from disk." ); } else { // I don't see why this should happen, but it will be left here, just in // case Java screws up. if (bytesSkipped > bytesRemaining) throw new InternalError( "This error is being thrown because the Java Virtual Machine has " + "skipped past the end of the requested offset. This has occured while " + "calling FileInputStream.skip(offset)." ); // NOTE: I am *FULLY AWARE* this is redundant, but the variable names are // the only thing that is very readable about this method. totalBytesSkipped += bytesSkipped; bytesRemaining -= bytesSkipped; } // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // THEN, Read the bytes from the file // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** byte[] retArr = new byte[len]; int arrPos = 0; // This one was already defined / declared in the previous part. Initialize it, but // don't re-declare it. bytesRemaining = len; // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // This loop exits when all (requested) bytes have been read, or EOFException! // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** while (bytesRemaining > 0) { int bytesRead = fis.read(retArr, arrPos, bytesRemaining); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Case 1: The EOF Marker was reached, before filling up the response-array // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** if (bytesRead == -1) if (bytesRemaining > 0) throw new EOFException( "The end of file '" + fileName + "' was reached before " + len + " bytes were read. Only " + arrPos + " bytes were read." ); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Yes, this seems redundant, but it's just the way it is // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // // arrPos ==> 0 ... retArr.length (retArr.length => input-param 'len') // bytesRemaining ==> 'len' ... 0 arrPos += bytesRead; bytesRemaining -= bytesRead; // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Case 2: Exactly the appropriate number of bytes were read. // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** if (arrPos == retArr.length) return retArr; // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Case 3: This should not be reachable! // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // // Java's FileInputStream.read method is supposed to stop when it has read // 'bytesRemaining' number of bytes! if (arrPos > retArr.length) throw new UnreachableError(); } // One of the cases inside the loop body must fire before the loop ever actually exits, // unless I'm missing something! throw new UnreachableError(); } } /** * Attempts to read a {@code java.lang.Class} from a class-file. * * <BR /><BR />It is not neccessarily always knownst to the programmer what the * <I>Full-Package Class-Name</I> of the {@code class} that's inside the class-file actually * is. * * @param classFileName The name of any class-file on the File-System. * * @param possibleClassNames If the exact <B STYLE='color: red;'>Full-Package Name</B> of the * class being read is known, then that ought to be the only {@code String} passed to this * Var-Args {@code String}-Parameter. If there are multiple possibilities, pass all of them, * and all we be used in an attempt to parse & load this class. * * <BR /><BR /><B>DEVELOPER NOTE:</B> Perhaps I am stupid, but I cannot find any way to read * a class file, and then ask that class-file either: * * <BR /><BR /><UL CLASS=JDUL> * <LI>What the name of the {@code Class} in the Class-File is?</LI> * <LI>What the name of the {@code Package} being used in that Class-File is?</LI> * </UL> * * <BR /><BR />So, for now, a Var-Args {@code String}-Array is required. * * <BR /><BR />To add insult to injury, the standard Java Exception class * {@code 'TypeNotPresentException'} doesn't have a constructor that accepts a * {@code 'message'} parameter (it accepts a {@code 'typeName'}) parameter instead. As a * result, if this method throws that exception, the error-message printed has a few * 'extranneous characters' <B>BOTH</B> before the actual message, <B>AND</B> after it. It is * staying this way because Java's Description of that exception matches precisely with its * use here. * * @return An instance of {@code java.lang.Class} that was contained by the Class-File. * * @throws IOException Java may throw several exceptions while attempting to load * the {@code '.class'} file into a {@code byte[]} array. Such exceptions may include * {@code IOException}, {@code SecurityException}, {@code FileNotFoundException} etc... * * @throws TypeNotPresentException If none of the names listed in Var-Args {@code String[]} * Array parameter {@code 'possibleClassNames'} are consistent with * <B STYLE='color:red'><I>BOTH</I></B> the package-name <B STYLE='color:red;'>AND</B> the * class-name of the actual class that resides inside {@code 'classFileName'}, then this * exception will throw. * * <BR /><BR /><B>NOTE:</B> Rather than simply returning 'null', this {@code RuntimeException} * is thrown as a nicely worded error message is provided. */ public static Class<?> readClass(String classFileName, String... possibleClassNames) throws IOException { // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Load the entire '.class' file into a byte[] array. // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Now read the bytes directly into a byte[] array, courtesy of Torello.Java.FileRW byte[] byteArray = readBinary(classFileName); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Create a ClassLoader - and convert "byte[]" into "Class<?> summarySorterClass" // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // NOTE: The commented lines below will not work if there is a "Package Name" given to the // class (in the '.java' file). It is better to just read the raw class-file bytes // into a Java byte[] array. SPECIFICALLY, if class is not inside of a directory // that is PRECISELY-CONSISTENT with the full-path package+class name, then the class // loader listed below will FAIL. (NOTE: If the package+class name is consisten, // then a programmer wouldn't need ANY OF THIS, and could simply call the normal // "Class.forName(fullPackageClassName)" to get the class!) // // ClassLoader cl = new URLClassLoader(new URL[] { new URL("file://" + path) }); // Class<?> ret = cl.loadClass(className); // // HOWEVER: Creating a new ClassLoader instance that accepts the byte-array (thereby // exporting the 'protected' method defineClass) *DOES* work. class ByteClassLoader extends ClassLoader { public Class<?> defineClass(String name, byte[] classBytes) { return defineClass(name, classBytes, 0, classBytes.length); } } ByteClassLoader cl = new ByteClassLoader(); Class<?> ret = null; StringBuilder sb = new StringBuilder(); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Make attempts to convert the byte[] array into a java.lang.Class // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** for (String fullClassName : possibleClassNames) try { return cl.defineClass(fullClassName, byteArray); } catch (NoClassDefFoundError e) { String errorMessage = e.getMessage(); if (errorMessage != null) sb.append(errorMessage + '\n'); } throw new TypeNotPresentException( "The Class-File: [" + classFileName + "] seems to have been successfully read, but " + "none of the user provided Canonical-Class Names (including a package) were " + "consistent with the actual name of the Class/Type inside that class file. Below " + "are listed the exception-messages received, which include both the actual/complete " + "canonical class-name, along with your user-provided guesses. Errors Saved:\n" + StrIndent.indent(sb.toString(), 4), null ); } } |