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 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022
|
/*
* Copyright (C) 2001-2013 Michael Fuchs
*
* This file is part of herold.
*
* herold is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* herold is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with herold. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dbdoclet.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dbdoclet.CreatePathException;
import org.dbdoclet.DeleteFileException;
import org.dbdoclet.FileAccessDeniedException;
import org.dbdoclet.RenameFileException;
import org.dbdoclet.ServiceException;
import org.dbdoclet.Sfv;
import org.dbdoclet.io.DirectoryFilter;
import org.dbdoclet.io.EndsWithFilter;
import org.dbdoclet.io.MimeType;
import org.dbdoclet.io.StartsWithFilter;
import org.dbdoclet.progress.ProgressEvent;
import org.dbdoclet.progress.ProgressListener;
import org.dbdoclet.template.TemplateTransformException;
import org.dbdoclet.template.TemplateTransformer;
/**
* Die Klasse <code>FileServices</code> stellt statische Methoden zur Verfügung, die
* Dateien und Dateverzeichnisse manipulieren und auswerten bereit.
*
* @author <a href="mailto:michael.fuchs@dbdoclet.org">Michael Fuchs</a>
* @version 8.0
*/
public class FileServices {
/** Alle Dateien */
public static final int ALL = 2;
/** Verwende den EndsWith-Filter */
public static final int ENDS_WITH = 1;
public static final String FSEP = System.getProperty("file.separator");
private static Log logger = LogFactory.getLog(FileServices.class);
/** Verwende den StartsWith-Filter */
public static final int STARTS_WITH = 0;
public static final Pattern PATTERN_ABSOLUTE_WINDOWS_PATH = Pattern
.compile("^([a-z,A-Z]:|/)/.*$");
/**
* @see #appendFileName(String dir, String filename)
*/
public static String appendFileName(File dir, String filename) {
if (dir == null) {
throw new IllegalArgumentException(
"The argument dir must not be null!");
}
return appendFileName(dir.getAbsolutePath(), filename);
}
/**
* Die Methode <code>appendFileName</code> hängt den Dateinamen and das
* Verzeichnis an.
*
* Falls der Dateinamen mit dem betriebsspezifischen Pfadtrennzeichen endet
* wird eine <code>IllegalArgumentException</code> ausgelöst.
*
* <div id="example_FileServices_appendFileName_1" title="Beispiel:">
*
* <pre>
*
* String path = System.getProperty("user.home");
*
* path = FileServices.appendPath(path, "logs");
* FileServices.createPath(path);
*
* path = FileServices.appendFileName(path, "Errors.log");
* File file = new File(path);
*
* </pre>
*
* </div>
*
*
*/
public static String appendFileName(String path1, String filename) {
if (path1 == null || path1.length() == 0) {
throw new IllegalArgumentException(
"The argument path1 must not be null!");
}
if (filename == null) {
throw new IllegalArgumentException(
"The argument filename must not be null!");
}
if (filename.trim().length() == 0) {
throw new IllegalArgumentException(
"The argument filename must not be empty!");
}
if (path1.endsWith(File.separator) == false) {
path1 += File.separator;
}
if (filename.startsWith(File.separator) == true
&& filename.length() > 1) {
filename = filename.substring(1);
}
if (filename.endsWith(File.separator) == true) {
throw new IllegalArgumentException("The name of file '" + filename
+ "' must not end with '" + File.separator + "'!");
}
if (filename.length() == 0) {
throw new IllegalArgumentException(
"The filename must not be of length 0!");
}
return path1 + filename;
}
public static String appendPath(File dir1, File dir2) {
if (dir1 == null) {
throw new IllegalArgumentException(
"The argument dir1 must not be null!");
}
if (dir2 == null) {
throw new IllegalArgumentException(
"The argument dir2 must not be null!");
}
return appendPath(dir1.getPath(), dir2.getPath());
}
public static String appendPath(File dir1, String path2) {
if (dir1 == null) {
throw new IllegalArgumentException(
"The argument dir1 must not be null!");
}
if (path2 == null) {
throw new IllegalArgumentException(
"The argument path2 must not be null!");
}
return appendPath(dir1.getPath(), path2);
}
/**
* Die Methode <code>appendPath</code> hängt das Verzeichnis path2 an das
* Verzeichnis path1.
*
* Der erstellte Verzeichnispfad endet in jedem Fall mit dem
* betriebsspezifischen Trennzeichen für Verzeichnisse.
*/
public static String appendPath(String path1, String path2) {
if (path1 == null || path1.length() == 0) {
throw new IllegalArgumentException(
"The argument path1 must not be null!");
}
if (path2 == null || path2.length() == 0) {
throw new IllegalStateException("The field path2 must not be null!");
}
path1 = path1.replace("/", File.separator);
path2 = path2.replace("/", File.separator);
if (path1.endsWith(File.separator) == false) {
path1 += File.separator;
}
if (path2.startsWith(File.separator) == true) {
if (path2.length() > File.separator.length()) {
path2 = path2.substring(File.separator.length());
}
}
if (path2.endsWith(File.separator) == false) {
path2 += File.separator;
}
return path1 + path2;
}
/**
* Die Methode <code>cleanRelatedFiles</code> löscht eine Datei oder ein
* Verzeichnis und alle "verwandten" Dateien und Verzeichnisse.
*
* Als verwandte Dateiobjekte werden alle Dateien und Verzeichnisse
* betrachtet, deren Dateinname aus dem Dateinamen der Referenzdatei mit
* angehängtem Bindestrich und einer Ziffer besteht. Falls eine
* Dateinamenserweiterung vorhanden ist, wird diese am Ende des Dateinamens
* erwartet, z.B. <code>Addressen-12.txt</code> ist verwand mit
* <code>Addressen.txt</code>.
*
* @param file
* <code>File</code>
* @exception IOException
*/
public static void cleanRelatedFiles(File file) throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
int index = 1;
String fileBase;
String fileExt;
String path;
fileBase = getFileBase(file.getCanonicalPath());
fileExt = getExtension(file.getCanonicalPath());
logger.debug("Verzeichnis aufräumen: " + file.getCanonicalPath());
while (file.exists() == true) {
try {
setWritable(file);
delete(file);
} catch (Exception oops) {
logger.fatal("FileServices.cleanRelatedFiles", oops);
}
path = fileBase + "-" + String.valueOf(index++);
if (fileExt != null && fileExt.trim().length() > 0) {
path += "." + fileExt;
}
file = new File(path);
logger.debug("Verzeichnis aufräumen: " + file.getCanonicalPath());
}
}
public static boolean contains(File file, String regex)
throws ServiceException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
if (regex == null) {
throw new IllegalArgumentException(
"The argument regex must not be null!");
}
BufferedReader reader = null;
try {
Pattern pattern = Pattern.compile(regex);
Matcher matcher;
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
matcher = pattern.matcher(line);
if (matcher.find()) {
return true;
}
}
return false;
} catch (IOException oops) {
throw new ServiceException(oops);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
public static boolean copyDir(File src, File dest) throws IOException {
if (src == null) {
throw new IllegalArgumentException(
"The argument src must not be null!");
}
if (dest == null) {
throw new IllegalArgumentException(
"The argument dest must not be null!");
}
return copyDir(src.getCanonicalPath(), dest.getCanonicalPath(), null,
null);
}
public static boolean copyDir(File src, File dest,
Map<String, String> filterSet) throws IOException {
if (src == null) {
throw new IllegalArgumentException(
"The argument src must not be null!");
}
if (dest == null) {
throw new IllegalArgumentException(
"The argument dest must not be null!");
}
return copyDir(src.getCanonicalPath(), dest.getCanonicalPath(), null,
filterSet, null, null);
}
public static boolean copyDir(File src, File dest, Pattern includePattern)
throws IOException {
if (src == null) {
throw new IllegalArgumentException(
"The argument src must not be null!");
}
if (dest == null) {
throw new IllegalArgumentException(
"The argument dest must not be null!");
}
if (includePattern == null) {
throw new IllegalArgumentException(
"The argument includePattern must not be null!");
}
Pattern[] patterns = new Pattern[1];
patterns[0] = includePattern;
return copyDir(src.getPath(), dest.getPath(), patterns, null, null,
null);
}
public static boolean copyDir(File src, String dest, int index)
throws IOException {
if (src == null) {
throw new IllegalArgumentException(
"The argument src must not be null!");
}
return copyDir(src.getCanonicalPath(), dest, index);
}
public static boolean copyDir(File src, String dest, int index,
ProgressListener listener, String resourceString)
throws IOException {
if (src == null) {
throw new IllegalArgumentException(
"The argument src must not be null!");
}
return copyDir(src.getCanonicalPath(), dest, index, listener,
resourceString);
}
public static boolean copyDir(String src, String dest) throws IOException {
return copyDir(src, dest, null, null, null, null);
}
public static boolean copyDir(String src, String dest, int index)
throws IOException {
return copyDir(src, dest, index, null, null);
}
/**
* Die Methode <code>copyDir</code> kopiert das Verzeichnis mit einem Teil
* seines übergeordneten Pfades in das angegebene Zielverzeichnis.
*
* @param src
* <code>String</code>
* @param dest
* <code>String</code>
* @param index
* <code>int</code>
* @exception IOException
*/
public static boolean copyDir(String src, String dest, int index,
ProgressListener listener, String resourceString)
throws IOException {
String path = normalizePath(src);
path = StringServices.chop(path, "/");
String name = getPathToken(path, index);
if (name == null) {
throw new FileNotFoundException(src);
}
for (int i = index; i > 0; i--) {
name = getPathToken(path, i);
dest = appendPath(dest, name);
logger.debug("Anlegen des Verzeichnisses " + dest + ".");
dest = normalizePath(dest);
FileServices.createPath(dest);
}
return copyDir(src, dest, null, null, listener, resourceString);
}
public static boolean copyDir(String src, String dest,
Map<String, String> filterSet) throws IOException {
return copyDir(src, dest, null, filterSet, null, null);
}
public static boolean copyDir(String src, String dest,
Pattern[] includePatterns) throws IOException {
return copyDir(src, dest, includePatterns, null, null, null);
}
/**
* Die Methode <code>copyDir</code> kopiert ein Verzeichnis und seinen
* Inhalt einschließlich aller Unterverzeichnissen.
*
* @param src
* Der Parameter <code>src</code> enthält das Quellverzeichnis,
* welches kopiert werden soll. Wird als Wert <code>null</code>
* übergeben existiert das Verzeichnis nicht oder der angegebene
* Pfad ist kein Verzeichnis, wird eine
* <code>IllegalArgumentException</code> ausglöst.
*
* @param dest
* Der Parameter <code>dest</code> enthält das Zielverzeichnis in
* das kopiert werden soll. Wird als Wert <code>null</code>
* übergeben oder ist der angegebene Pfad kein Verzeichnis, wird
* eine <code>IllegalArgumentException</code> ausglöst. Falls das
* Zielverzeichnis nicht existiert wird es angelegt.
*
* @exception IOException
* Falls beim Kopieren ein Ein/Ausgabefehler auftritt.
*/
public static boolean copyDir(String src, String dest,
Pattern[] includePatterns, Map<String, String> filterSet,
ProgressListener listener, String resourceString)
throws IOException {
String msg;
src = normalizePath(src);
dest = normalizePath(dest);
logger.debug(src + " -> " + dest);
if (src == null) {
throw new IllegalArgumentException("Parameter src is null!");
}
if (dest == null) {
throw new IllegalArgumentException("Parameter dest is null!");
}
File srcDir = new File(src);
if (srcDir.exists() == false) {
throw new FileNotFoundException("Source path '"
+ srcDir.getAbsolutePath() + "' dosen't exist!");
}
if (srcDir.isDirectory() == false) {
throw new IllegalArgumentException("Source path '"
+ srcDir.getAbsolutePath() + "' is not a directory!");
}
File destDir = FileServices.createPath(dest);
if (destDir.isDirectory() == false) {
throw new IllegalArgumentException("Destination path '"
+ destDir.getAbsolutePath() + "' is not a directory!");
}
src = normalizePath(srcDir.getCanonicalPath());
dest = normalizePath(destDir.getCanonicalPath());
File[] files = srcDir.listFiles();
File destFile;
String destFileName;
for (int i = 0; i < files.length; i++) {
destFileName = appendFileName(dest, files[i].getName());
destFile = new File(destFileName);
if (files[i].isDirectory()) {
String newSrc = files[i].getCanonicalPath();
newSrc = normalizePath(newSrc);
String newDest = StringServices.replace(newSrc, src, dest);
copyDir(newSrc, newDest, includePatterns, filterSet, listener,
resourceString);
if (includePatterns != null) {
File newDestDir = new File(newDest);
if (newDestDir.list().length == 0) {
delete(newDestDir);
}
}
}
if (includePatterns != null) {
boolean doCopy = false;
for (int p = 0; p < includePatterns.length; p++) {
Matcher matcher = includePatterns[p].matcher(destFileName);
if (matcher.matches() == true) {
doCopy = true;
break;
}
}
if (doCopy == false) {
continue;
}
}
if (files[i].isFile()) {
if (listener != null) {
logger.debug("Firing progress event.");
if (resourceString != null) {
msg = MessageFormat.format(resourceString,
files[i].getPath(), destFile.getPath());
} else {
msg = files[i].getName();
}
if (listener.progress(new ProgressEvent(msg, false)) == false) {
return false;
}
}
logger.debug(files[i].getAbsolutePath() + " -> "
+ destFile.getAbsolutePath());
if (filterSet == null || isBinary(files[i])) {
FileInputStream in;
FileOutputStream out;
in = new FileInputStream(files[i]);
out = new FileOutputStream(destFile);
int n = 0;
byte[] buffer = new byte[4096];
while ((n = in.read(buffer, 0, 4096)) != -1) {
out.write(buffer, 0, n);
}
in.close();
out.flush();
out.close();
if (destFile.exists() == false) {
throw new IOException("Couldn't create file "
+ destFileName + "!");
}
if (destFile.length() != files[i].length()) {
throw new IOException("Files differ after copy: "
+ destFileName + "!");
}
} else {
try {
TemplateTransformer trafo = TemplateTransformer
.newInstance(files[i]);
trafo.transform(filterSet, destFile);
} catch (TemplateTransformException oops) {
IOException ioe = new IOException(
"TemplateTransformException: "
+ oops.getMessage());
ioe.initCause(oops);
ioe.fillInStackTrace();
throw ioe;
}
if (destFile.exists() == false) {
throw new IOException("Couldn't create file "
+ destFileName + "!");
}
}
}
}
return true;
}
public static boolean copyDir(String src, String dest,
ProgressListener listener, String resourceString)
throws IOException {
return copyDir(src, dest, null, null, listener, resourceString);
}
public static void copyFileToDir(File src, File destdir) throws IOException {
copyFileToDir(src.getPath(), destdir.getPath());
}
/**
* Die Methode <code>copyFileToDir</code> kopiert eine einzelne Datei in das
* angegebene Zielverzeichnis.
*
* Falls das Zielverzeichnis nicht existiert, wird es angelegt.
*
* Die Datei wird nur kopiert, falls die Quelldatei neuer als die Zieldatei
* ist.
*
* @exception IOException
* falls ein Fehler beim Kopieren auftritt.
*/
public static void copyFileToDir(String src, String destdir)
throws IOException {
File file;
if (src == null) {
throw new IllegalArgumentException("Parameter src is null!");
}
file = new File(src);
if (file.exists() == false) {
throw new IllegalArgumentException("Parameter src ("
+ file.getAbsolutePath() + ") can not be found!");
}
if (file.isFile() == false) {
throw new IllegalArgumentException("Parameter src ("
+ file.getAbsolutePath() + ") is not a normal file!");
}
if (destdir == null) {
throw new IllegalArgumentException("Parameter destdir is null!");
}
file = new File(destdir);
if (file.exists() && file.isDirectory() == false) {
throw new IllegalArgumentException("Parameter destdir ("
+ file.getAbsolutePath() + ") is not a directory!");
}
File srcFile = new File(src);
String path = appendFileName(destdir, srcFile.getName());
File destFile = new File(path);
FileInputStream in;
FileOutputStream out;
in = new FileInputStream(srcFile);
out = new FileOutputStream(destFile);
int n = 0;
byte[] buffer = new byte[4096];
while ((n = in.read(buffer, 0, 4096)) != -1) {
out.write(buffer, 0, n);
}
in.close();
out.close();
}
/**
* Die Methode <code>copyFileToFile</code> kopiert eine einzelne Datei,
* falls die Quelldatei neuer als die Zieldatei ist.
*
* Falls das Zielverzeichnis nicht existiert, wird es angelegt.
*
* @throws IOException
* falls ein Fehler beim Kopieren auftritt.
*/
public static void copyFileToFile(File src, File dest) throws IOException {
copyFileToFile(src.getAbsolutePath(), dest.getAbsolutePath(), null);
}
public static void copyFileToFile(File srcFile, File destFile,
Map<String, String> filterSet) throws IOException {
if (srcFile == null) {
throw new IllegalArgumentException("Parameter srcFile is null!");
}
if (srcFile.exists() == false) {
throw new IllegalArgumentException(
"Parameter srcFile doesn't exist! '"
+ srcFile.getAbsolutePath() + "'");
}
if (srcFile.isFile() == false) {
throw new IllegalArgumentException(
"Parameter srcFile is not a normal file! '"
+ srcFile.getAbsolutePath() + "'");
}
if (destFile == null) {
throw new IllegalArgumentException("Parameter destFile is null!");
}
if (srcFile.exists() && srcFile.isFile() == false) {
throw new IllegalArgumentException(
"Parameter destFile is not a normal file! '"
+ srcFile.getAbsolutePath() + "'");
}
if (srcFile.equals(destFile)) {
return;
}
if (destFile.exists() == true && destFile.canWrite() == false) {
throw new FileAccessDeniedException(destFile);
}
String srcPath = srcFile.getCanonicalPath();
srcPath = normalizePath(srcPath);
String destPath = destFile.getCanonicalPath();
destPath = normalizePath(destPath);
if (destPath.equals(srcPath)) {
logger.warn("Copy: Files " + srcPath + " and " + destPath
+ " are identical!");
return;
}
String destParentDir = destFile.getParent();
if (destParentDir != null && destParentDir.length() > 0) {
createPath(destParentDir);
}
if (filterSet == null || isBinary(srcFile)) {
FileInputStream in;
FileOutputStream out;
in = new FileInputStream(srcFile);
out = new FileOutputStream(destFile);
int n = 0;
byte[] buffer = new byte[4096];
while ((n = in.read(buffer, 0, 4096)) != -1) {
out.write(buffer, 0, n);
}
in.close();
out.flush();
out.close();
} else {
try {
TemplateTransformer trafo = TemplateTransformer
.newInstance(srcFile);
trafo.transform(filterSet, destFile);
} catch (TemplateTransformException oops) {
IOException ioe = new IOException(
"TemplateTransformException: " + oops.getMessage());
ioe.initCause(oops);
ioe.fillInStackTrace();
throw ioe;
}
}
}
public static void copyFileToFile(String src, String dest)
throws IOException {
copyFileToFile(new File(src), new File(dest), null);
}
/**
* Die Methode <code>copyFileToFile</code> kopiert eine einzelne Datei.
* Falls das Zielverzeichnis nicht existiert, wird es angelegt.
*
* @throws IOException
* falls ein Fehler beim Kopieren auftritt.
*/
public static void copyFileToFile(String src, String dest,
Map<String, String> filterSet) throws IOException {
copyFileToFile(new File(src), new File(dest), filterSet);
}
public static File createParentDir(File dir) throws IOException {
if (dir == null) {
throw new IllegalArgumentException(
"The argument dir must not be null!");
}
File parentDir = dir.getParentFile();
if (parentDir == null) {
return null;
}
return createPath(parentDir);
}
/**
* Legt ein neues Verzeichnis an.
*
* Falls das Verzeichnis bereits existiert, wird dieses ohne Fehlermeldung
* zurückgeliefert. Existiert das Verzeichnis nicht und das Anlegen schlägt
* fehl wird eine Ausnahme erzeugt.
*
* <b>Vorbedingung:</b> Wird als <code>dir</code>-Parameter
* <code>null</code> Übergeben, so wird eine
* <code>IllegalArgumentException</code> ausgelöst.
*
* @exception IOException
* falls das Anlegen des Verzeichnisses fehlschlägt.
*/
public static File createPath(File dir) throws IOException {
if (dir == null) {
throw new IllegalArgumentException(
"The argument dir must not be null!");
}
String dirName = dir.getCanonicalPath();
if (JvmServices.isWindows()) {
if (dirName != null && dirName.length() > 255) {
throw new CreatePathException(dirName,
CreatePathException.PATH_TOO_LONG);
}
}
if (dir.exists() == false) {
if (dir.mkdirs() == false && dir.exists() == false) {
ArrayList<File> pathList = new ArrayList<File>();
pathList.add(0, dir);
File parent = dir.getParentFile();
File next = dir;
while (parent != null && parent.exists() == false) {
pathList.add(0, parent);
next = parent;
parent = parent.getParentFile();
}
if (parent != null && parent.exists() == true) {
if (parent.isDirectory() == false) {
throw new CreatePathException(next.getCanonicalPath(),
CreatePathException.FILE_PARENT);
}
if (parent.canWrite() == false || parent.canRead() == false) {
throw new CreatePathException(next.getCanonicalPath(),
CreatePathException.PERMISSION_DENIED);
}
}
throw new CreatePathException(dir.getCanonicalPath());
}
}
return dir;
}
/**
* Legt ein neues Verzeichnis an.
*
* Falls das Verzeichnis bereits existiert, wird dieses ohne Fehlermeldung
* zurückgeliefert. Existiert das Verzeichnis nicht und das Anlegen schlägt
* fehl wird eine Ausnahme erzeugt.
*
* <b>Vorbedingung:</b>Wird als <code>path</code>-Parameter
* <code>null</code> übergeben, so wird eine
* <code>IllegalArgumentException</code> ausgelöst.
*
* @throws IOException
* falls das Anlegen des Verzeichnisses fehlschlägt.
*/
public static File createPath(String path) throws IOException {
if (path == null) {
throw new IllegalArgumentException("Parameter path is null!");
}
return createPath(new File(path));
}
public static File createUniqueFile(File file) throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
int index = 1;
String fileBase;
String fileExt;
String path;
fileBase = getFileBase(file.getCanonicalPath());
fileExt = getExtension(file.getCanonicalPath());
while (file.exists() == true) {
path = fileBase + "-" + String.valueOf(index++);
if (fileExt != null && fileExt.trim().length() > 0) {
path += "." + fileExt;
}
file = new File(path);
}
return file;
}
public static String cutPrefixPathItems(String path, int length) {
if (path == null) {
throw new IllegalArgumentException(
"The argument path must not be null!");
}
if (length < 0) {
throw new IllegalArgumentException(
"The argument length must not be < 0!");
}
String buffer = normalizePath(path);
buffer = StringServices.cutPrefix(buffer, "/");
while (buffer.endsWith("/")) {
buffer = StringServices.cutSuffix(buffer, "/");
}
int index = buffer.indexOf("/");
int counter = 1;
while (index > 0 && counter < length) {
index = buffer.indexOf("/", index + 1);
counter++;
}
return buffer.substring(index + 1);
}
public static int delete(File file) throws IOException {
if (file == null) {
return 0;
}
return delete(file.getPath(), null);
}
public static int delete(File file, ProgressListener listener)
throws IOException {
return delete(file.getPath(), listener, null);
}
/**
* Die Methode <code>delete</code> löscht alle regulären Dateien aus dem
* Verzeichnis, die auf den regulären Asudruck passen.
*
* @param dir
* a <code>File</code> value
* @param regexp
* a <code>String</code> value
* @return an <code>int</code> value
* @exception IOException
* if an error occurs
*/
public static int delete(File dir, String regexp) throws IOException {
if (dir == null) {
return 0;
}
ArrayList<File> fileList = new ArrayList<File>();
FindServices.findFile(dir, regexp, false, fileList);
for (File file : fileList) {
delete(file);
}
return fileList.size();
}
/**
* Die Methode <code>delete</code> löscht eine Datei oder ein Verzeichnis
* und alle darin enthaltenen Dateien und Unterverzeichnisse.
*/
public static int delete(String path) throws IOException {
return delete(path, null);
}
public static int delete(String path, ProgressListener listener)
throws IOException {
return delete(path, listener, null);
}
/**
* Die Methode <code>delete</code> löscht eine Datei oder ein Verzeichnis
* und alle darin enthaltenen Dateien und Unterverzeichnisse.
*/
public static int delete(String path, ProgressListener listener,
String resourceString) throws IOException {
return delete(new File(path), listener, resourceString);
}
/**
* Die Methode <code>delete</code> <b>löscht</b> eine Datei oder ein
* Verzeichnis und alle darin enthaltenen Dateien und Unterverzeichnisse.
*/
public static int delete(File node, ProgressListener listener,
String resourceString) throws IOException {
String msg;
logger.debug("Lösche Pfad " + node + ".");
if (node == null) {
return 0;
}
boolean rc;
int counter = 0;
if (node.exists() == false) {
logger.debug("Der Pfad " + node.getAbsolutePath()
+ " existiert nicht!");
return 0;
}
if (node.isFile() == true) {
rc = node.delete();
if (rc == false) {
throw new DeleteFileException(node);
/*
* if (JvmServices.isWindows()) {
*
* String[] cmd = new String[4]; cmd[0] = "del"; cmd[1] = "/F";
* cmd[2] = "/Q"; cmd[3] = node.getCanonicalPath();
*
* ExecResult result = ExecServices.exec(cmd);
*
* if (result.getFailed()) { throw new
* DeleteFileException(node); }
*
* } else if (JvmServices.isUnix()) {
*
* String[] cmd = new String[3]; cmd[0] = "rm"; cmd[1] = "-f";
* cmd[2] = node.getCanonicalPath();
*
* ExecResult result = ExecServices.exec(cmd);
*
* if (result.getFailed()) { throw new
* DeleteFileException(node); }
*
* } else {
*
* }
*/
}
}
if (node.isDirectory() == true) {
File[] list = node.listFiles();
if (list != null) {
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
counter += delete(list[i].getAbsolutePath(), listener,
resourceString);
} else {
rc = list[i].delete();
if (rc == false) {
throw new DeleteFileException(node);
}
}
}
}
counter++;
if (listener != null) {
logger.debug("Firing progress event.");
if (resourceString != null) {
msg = MessageFormat.format(resourceString, node.getPath());
} else {
msg = node.getName();
}
listener.progress(new ProgressEvent(msg, false));
}
rc = node.delete();
if (rc == false) {
throw new DeleteFileException(node);
}
}
if (node.exists() == true) {
throw new DeleteFileException(node);
}
return counter;
}
/**
* Die Methode <code>delete</code> löscht alle Dateien aus dem Verzeichnis
* <code>path</code> die auf den Filter <code>filter</code> passen.
*
* Die Art des Filters wird durch den Filtertyp bestimmt. Der Typ kann den
* Anfang oder das Ende eines Dateinamens überpüfen.
*
* Folgende Type können verwendet werden:
* <ul>
* <li>STARTS_WITH - Testet den Anfang des Dateinamens</li>
* <li>ENDS_WITH - Testet das Ende des Dateinamens</li>
* <li>ALL - Trifft auf alle Dateien zu</li>
* </ul>
*/
public static void delete(String path, String filter, int type) {
if (path == null) {
return;
}
File dir = new File(path);
if (dir.exists() == false) {
return;
}
File[] list;
switch (type) {
case STARTS_WITH:
list = dir.listFiles(new StartsWithFilter(filter));
break;
case ENDS_WITH:
list = dir.listFiles(new EndsWithFilter(filter));
break;
case ALL:
list = dir.listFiles();
break;
default:
return;
}
for (int i = 0; i < list.length; i++) {
list[i].delete();
}
}
public static void deleteEmptyDirs(File dir) throws IOException {
if (dir == null) {
throw new IllegalArgumentException(
"The argument dir must not be null!");
}
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
deleteEmptyDirs(list[i]);
if (list[i].list().length == 0) {
delete(list[i]);
}
}
}
}
public static void deleteEmptyDirs(String path) throws IOException {
deleteEmptyDirs(new File(path));
}
/**
* Die Methode <code>getAbsoluteDirName</code> liefert das übergeordnete
* Verzeichnis des angegebenen Pfades als absoluten Pfad.
*/
public static String getAbsoluteDirName(String filename) {
if (filename == null) {
throw new IllegalArgumentException("Parameter filename is null!");
}
if (filename.length() == 0) {
throw new IllegalArgumentException("Parameter filename is null!");
}
File file = new File(filename);
String path = file.getAbsolutePath();
int index = path.lastIndexOf(File.separator);
if (index == -1) {
return ".";
}
path = path.substring(0, index);
return path;
}
/**
* Die Methode <code>getDirName</code> liefert das übergeordnete Verzeichnis
* des angegebenen Pfades.
*/
public static String getDirName(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("Parameter fileName is null!");
}
if (fileName.length() == 0) {
throw new IllegalArgumentException("Parameter fileName is null!");
}
fileName = StringServices.chop(fileName, File.separator);
int index = fileName.lastIndexOf(File.separator);
if (index == -1) {
return ".";
}
String path = fileName.substring(0, index);
return path;
}
/**
* Die Methode <code>getExtension</code> liefert die Dateinamenerweiterung
* des angegebenen Pfadnamens.
*
* Die Dateinamenerweiterung muß mit einem Punkt vom Rest getrennt sein. Der
* Punkt wird nicht mit zurückgeliefert.
*/
public static String getExtension(String filename) {
if (filename == null) {
throw new IllegalArgumentException("Parameter filename is null!");
}
// strip any directory information
filename = getFileName(filename);
int index = filename.lastIndexOf(".");
if (index == -1) {
return "";
}
filename = filename.substring(index + 1);
return filename;
}
public static String getFileBase(File file) {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
return getFileBase(file.getPath());
}
/**
* Die Methode <code>getFileBase</code> liefert den Pfadnamen ohne
* Dateinamenerweiterung.
*
* Als Dateinamenerweiterung wird der letzte Teil eines Pfadnamens
* angesehen, der mit einem Punkt vom Rest abgetrennt ist.
*
* Falls der Pfad Verzeichnisse enthält werden diese nicht entfernt. Um den
* letzten Teil der Pfadangabe zu erhalten kann die Methode
* <code>getFileName</code> verwendet werden.
*
* <div title="example">
* <p>
* Der Pfad <code>/tmp/file.txt</code> wird zu <code>/tmp/file</code>.
* </div>
*
*/
public static String getFileBase(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("Parameter fileName is null!");
}
int index = fileName.lastIndexOf(".");
if (index == -1) {
return fileName;
}
fileName = fileName.substring(0, index);
return fileName;
}
/**
* Die Methode <code>getFileName</code> liefert den letzten Teil einer
* Pfadangabe, üblicherweise einen Dateinamen.
*/
public static String getFileName(String path) {
if (path == null) {
throw new IllegalArgumentException("Parameter path is null!");
}
path = normalizePath(path);
path = StringServices.chop(path, "/");
File file = new File(path);
return file.getName();
}
public static String getMimeType(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException(
"The argument fileName must not be null!");
}
String type = null;
String[] cmd = new String[5];
cmd[0] = "file";
cmd[1] = "-b";
cmd[2] = "-p";
cmd[3] = "-i";
cmd[4] = fileName;
ExecResult result = ExecServices.exec(cmd);
type = result.getOutput();
type = StringServices.trim(type, Sfv.LSEP);
type = StringServices.trim(type, ' ');
if (result.failed() == false && type != null && type.length() > 0) {
logger.debug("(file -b -pi -i " + fileName + ") -e type=" + type);
return type;
}
String name = FileServices.getFileName(fileName.toLowerCase());
name = StringServices.cutSuffix(name, ",v");
FileNameMap fnm = URLConnection.getFileNameMap();
type = fnm.getContentTypeFor(name);
if (type != null && type.trim().length() > 0) {
logger.debug("(FileNameMap " + name + ") type=" + type);
return type;
}
String ext = FileServices.getExtension(name);
MimeType mimeType = MimeType.findByExtension(ext);
if (mimeType != null) {
logger.debug("(MimeType " + name + ") type="
+ mimeType.getMimeType());
return mimeType.getMimeType();
}
File file = new File(fileName);
boolean nullByte = false;
if (file.exists() && file.canRead()) {
FileReader reader = null;
try {
reader = new FileReader(file);
int c = reader.read();
while (c != -1) {
c = reader.read();
if (c == 0) {
nullByte = true;
break;
}
}
} catch (Throwable oops) {
logger.fatal("FileServices.isBinary", oops);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException oops) {
logger.fatal("FileServices.isBinary reader.close() ", oops);
}
}
}
if (nullByte == true) {
logger.debug("(No MimeType Found, Null Byte) " + name
+ ") type=application/octet-stream");
return "application/octet-stream";
} else {
logger.debug("(No MimeType Found " + name + ") type=text/plain");
return "text/plain";
}
}
public static String getPathHead(String path, int length) {
if (path == null) {
throw new IllegalArgumentException(
"The argument path must not be null!");
}
if (length < 0) {
throw new IllegalArgumentException(
"The argument length must not be < 0!");
}
path = normalizePath(path);
String subPath = path;
int index = path.indexOf("/");
int counter = 0;
while (index > 0 && counter < length) {
index = path.indexOf("/", index + 1);
counter++;
}
if (index > 0) {
subPath = path.substring(0, index);
}
return subPath;
}
public static String getPathTail(String path, int length) {
if (path == null) {
throw new IllegalArgumentException(
"The argument path must not be null!");
}
if (length < 0) {
throw new IllegalArgumentException(
"The argument length must not be < 0!");
}
path = StringServices.replace(path, FSEP, "/");
String subPath = path;
int index = path.lastIndexOf("/");
int counter = 1;
while (index > 0 && counter < length) {
index = path.lastIndexOf("/", index - 1);
counter++;
}
if (index > 0) {
subPath = path.substring(index + 1);
}
return subPath;
}
/**
* Die Methode <code>getPathToken</code> liefert einen bestimmenten Teil
* eines Pfades.
*
* Der Pfad wird von <b>hinten</b> nach vorne beginnend mit der Ziffer 1
* durchnummeriert.
*
* @param path
* <code>String</code>
* @param index
* <code>int</code>
* @return <code>String</code>
*/
public static String getPathToken(String path, int index) {
if (index == 0)
return "";
if (path == null) {
throw new IllegalArgumentException(
"The argument path must not be null!");
}
if (index < 0) {
throw new IllegalArgumentException(
"The argument index must not be < 0!");
}
String buffer = normalizePath(path);
buffer = StringServices.chop(buffer, "/");
logger.debug("buffer = " + buffer);
int indexStart = buffer.length();
int indexEnd = indexStart;
for (int i = 0; i < index; i++) {
indexEnd = indexStart;
indexStart = buffer.lastIndexOf('/', indexStart - 1);
logger.debug("start = " + indexStart + ", end = " + indexEnd);
if (indexStart == -1) {
return null;
}
}
String token = buffer.substring(indexStart + 1, indexEnd);
logger.debug("path token [" + index + "] = '" + token + "'.");
return token;
}
public static int getPathTokenCount(String path) {
logger.debug("#1 path=" + path);
if (path == null || path.trim().length() == 0) {
return 0;
}
path = normalizePath(path);
path = StringServices.trim(path, '/');
logger.debug("#2 path=" + path);
int index = path.indexOf("/");
logger.debug("index=" + index);
int counter = 1;
while (index > 0) {
index = path.indexOf("/", index + 1);
logger.debug("index=" + index);
counter++;
}
logger.debug("counter=" + counter);
return counter;
}
public static String getValueOfKey(File file, String key)
throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
if (key == null) {
throw new IllegalArgumentException(
"The argument key must not be null!");
}
key = key.trim();
if (key.endsWith("=") == false) {
key += "=";
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith(key) == true) {
if (line.length() <= key.length()) {
return "";
} else {
return line.substring(key.length() + 1);
}
}
}
return "";
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
public static boolean hasSubdirectory(File dir, String name) {
if (dir == null) {
return false;
}
if (name == null || name.length() == 0) {
return false;
}
String[] listing = dir.list();
if (listing == null) {
return false;
}
for (int i = 0; i < listing.length; i++) {
if (name.equals(listing[i])) {
return true;
}
}
return false;
}
public static String info(File file) throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
StringBuffer buffer = new StringBuffer();
buffer.append("path=" + file.getCanonicalPath());
if (file.exists() == false) {
buffer.append(",exists=false");
return buffer.toString();
}
buffer.append(",size=" + file.length());
return buffer.toString();
}
/**
* Liefert <code>true</code>, falls die Zeichenkette einen absoluten Pfad
* repräsentiert.
*/
public static boolean isAbsolutePath(String path) {
if (path == null) {
throw new IllegalArgumentException(
"The argument path must not be null!");
}
String buffer = new String(path);
buffer = StringServices.replace(buffer, File.separator, "/");
buffer = buffer.toLowerCase();
if (buffer.startsWith("/")) {
return true;
}
if (JvmServices.isWindows()) {
if (PATTERN_ABSOLUTE_WINDOWS_PATH.matcher(buffer).matches()) {
return true;
}
}
return false;
}
public static boolean isBinary(File file) {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
return isBinary(file.getAbsolutePath());
}
public static boolean isBinary(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException(
"The argument fileName must not be null!");
}
String mimeType = getMimeType(fileName);
logger.debug("mimeType=" + mimeType);
if (mimeType.startsWith("image/")) {
return true;
}
if (mimeType.startsWith("video/")) {
return true;
}
if (mimeType.startsWith("audio/")) {
return true;
}
if (mimeType.equals("application/octet-stream")
|| mimeType.equals("application/pdf")
|| mimeType.equals("application/postscript")
|| mimeType.equals("application/x-cpio")
|| mimeType.equals("application/x-dvi")
|| mimeType.equals("application/x-gtar")
|| mimeType.equals("application/x-tar")
|| mimeType.equals("application/x-ustar")
|| mimeType.equals("application/x-troff-msvideo")
|| mimeType.equals("application/zip")) {
return true;
}
File file = new File(fileName);
boolean nullByte = false;
if (file.exists() && file.canRead()) {
FileReader reader = null;
try {
reader = new FileReader(file);
int c = reader.read();
while (c != -1) {
c = reader.read();
if (c == 0) {
nullByte = true;
break;
}
}
} catch (Throwable oops) {
logger.fatal("FileServices.isBinary", oops);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException oops) {
logger.fatal("FileServices.isBinary reader.close() ", oops);
}
}
}
if (nullByte == true) {
return true;
}
return false;
}
public static boolean isEmptyDirectory(File file) {
if (file.isDirectory() == false) {
return false;
}
File[] list = file.listFiles();
if (list.length == 0) {
return true;
} else {
return false;
}
}
/**
* Die Methode <code>move</code> verschiebt eine Datei in ein anderes
* Verzeichnis.
*/
public static void move(String src, String destdir) throws IOException {
if (src == null) {
throw new IllegalArgumentException(
"The argument src must not be null!");
}
if (destdir == null) {
throw new IllegalArgumentException(
"The argument destdir must not be null!");
}
File srcFile = new File(src);
File destFile = new File(destdir + File.separator + srcFile.getName());
if (srcFile.equals(destFile)) {
return;
}
boolean rc = srcFile.renameTo(destFile);
if (rc == false) {
throw new RenameFileException(srcFile, destFile);
}
}
/**
* Die Methode <code>newer</code> vergleicht ob die 1. Datei neuer als die
* 2, Datei ist. Falls die 2. Datei nicht existiert wird true zurückgegeben.
*/
public static boolean newer(File f1, File f2) {
if (f1 == null || f1.exists() == false) {
return false;
}
if (f2 == null || f2.exists() == false) {
return true;
}
if (f1.lastModified() >= f2.lastModified()) {
return true;
} else {
return false;
}
}
/**
* Die Methode <code>newer</code> vergleicht 2 Dateien oder Verzeichnisse
* bezüglich des Datums ihrer letzten Änderung.
*
* Requires: Beide Dateien/Verzeichnisse müssen existieren.
*/
public static boolean newer(String f1, String f2) {
return newer(new File(f1), new File(f2));
}
/**
* Die Methode <code>normalizePath</code> konvertiert den angegegebenen Pfad
* in ein Standardformat.
*
* <ol>
* <li>Weißraum am Anfang oder Ende der Zeichenkette wird entfernt.</li>
* <li>Alle betriebssystemspezifischen Trennzeichen werden in einen
* Schrägstrich umgewandelt.</li>
* <li>Falls der Pfad einen absoluten Pfad repäsentiert, werden redundante
* Angaben bereinigt, z.B. <code>/C:/temp</code> wird zu
* <code>C:/temp</code>.</li>
* <ol>
*
* @param path
* <code>String</code>
* @return <code>String</code>
*/
public static String normalizePath(String path) {
if (path == null) {
throw new IllegalArgumentException(
"The argument path must not be null!");
}
path = new String(path);
File file = new File(path);
path = path.trim();
path = StringServices.replace(path, File.separator, "/");
while (isAbsolutePath(path) && path.length() > 1) {
String buffer = path.substring(1);
if (isAbsolutePath(buffer)) {
path = buffer;
} else {
break;
}
}
if (isAbsolutePath(path)) {
path = StringServices.lowerFirstLetter(path);
}
if (file.exists() && file.isDirectory() && path.endsWith("/") == false) {
path += "/";
}
return path;
}
/**
* Die Methode <code>pkgToPath</code> wandelt den Namen eines Java Packages
* in einen Verzeichnispfad um.
*/
public static String pkgToPath(String pkg) {
if (pkg == null) {
throw new IllegalArgumentException(
"The argument pkg must not be null!");
}
String path = StringServices.replace(pkg, ".", File.separator);
return path;
}
public static String readLine(File file, int lineIndex) throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
if (lineIndex < 0) {
throw new IllegalArgumentException(
"The argument lineIndex must not be < 0!");
}
int count = 0;
if (file != null && file.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
while (line != null) {
if (count == lineIndex) {
reader.close();
return line;
}
line = reader.readLine();
count++;
}
reader.close();
}
return null;
}
public static Object[] readToArray(File file) throws IOException {
return readToArray(file, "UTF-8");
}
public static Object[] readToArray(File file, String encoding)
throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
if (encoding == null) {
throw new IllegalArgumentException(
"The argument encoding must not be null!");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), encoding));
Object[] array = null;
try {
ArrayList<String> list = new ArrayList<String>();
String line = reader.readLine();
while (line != null) {
list.add(line);
line = reader.readLine();
}
int index = 0;
array = new Object[list.size()];
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
line = iterator.next();
array[index++] = line;
}
} finally {
reader.close();
}
return array;
}
public static byte[] readToByteArray(File file) throws IOException {
if (file == null) {
return null;
}
if (file.exists() == false) {
return null;
}
FileInputStream fis = new FileInputStream(file);
int off = 0;
long fileLength = file.length();
if (fileLength > Integer.MAX_VALUE) {
logger.error("The file is too big (>" + Integer.MAX_VALUE + ")!");
fis.close();
return null;
}
int length = (int) fileLength;
int size = length;
byte[] buffer = new byte[length];
int count;
try {
while ((count = fis.read(buffer, off, size)) != -1) {
off += count;
if ((length - off) < size) {
size = length - off;
if (size < 1) {
break;
}
}
if (off < 0) {
logger.error("Argument off must not be negative: off="
+ off + ", count=" + count + ", len=" + size
+ ", b.length=" + length);
}
if (size < 0) {
logger.error("Argument len must not be negative: off="
+ off + ", count=" + count + ", len=" + size
+ ", b.length=" + length);
}
if (size > (length - off)) {
logger.error("Argument len must not be negative: off="
+ off + ", count=" + count + ", len=" + size
+ ", b.length=" + length);
}
}
} finally {
fis.close();
}
return buffer;
}
public static String readToString(File file) throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
return readToString(file, "UTF-8");
}
public static String readToString(File file, String encoding)
throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
FileInputStream fis = new FileInputStream(file);
String buffer = readToString(fis, encoding);
fis.close();
return buffer;
}
public static String readToString(InputStream is) throws IOException {
return readToString(is, "UTF-8");
}
public static String readToString(InputStream is, String encoding)
throws IOException {
if (is == null) {
throw new IllegalArgumentException(
"The argument is must not be null!");
}
if (encoding == null) {
throw new IllegalArgumentException(
"The argument encoding must not be null!");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is,
encoding));
StringBuffer buffer = new StringBuffer();
char[] data = new char[4096];
int count;
try {
while ((count = reader.read(data)) > 0) {
buffer.append(data, 0, count);
}
} finally {
reader.close();
}
return buffer.toString();
}
public static String readToString(String fileName) throws IOException {
if (fileName == null) {
throw new IllegalArgumentException(
"The argument fileName must not be null!");
}
return readToString(new File(fileName), "UTF-8");
}
public static String readToString(String fileName, String encoding)
throws IOException {
if (fileName == null) {
throw new IllegalArgumentException(
"The argument fileName must not be null!");
}
return readToString(new File(fileName), encoding);
}
/**
* Die Methode <code>relativePath</code> ermittelt den relativen Pfad um vom
* Verzeichnis <code>start</code> zum Verzeichnis <code>dest</code> zu
* gelangen. Falls kein relativer Pfad ermittelt werden kann wird der
* absolute Pfad von <code>dest</code> zurückgeliefert.
*
* Werden relative Pfade übergeben, so werden diese mit Hilfe der Methode
* {@link File#getCanonicalFile()} in absolute PFade umgewandelt. Diese
* Methode ermittelt Pfad anscheinend anhand des Rückgabewertes von
* <code>System.getProperty("user.dir")</code>. Der Wert ist also nicht
* vohersagbar und ist abhängig vom aktuellen Arbeitsverzeichnis.
*
* @throws IOException
*/
public static String relativePath(File start, File dest) throws IOException {
if (start == null) {
throw new IllegalArgumentException(
"The argument start must not be null!");
}
if (dest == null) {
throw new IllegalArgumentException(
"The argument dest must not be null!");
}
File from = new File(start.getCanonicalPath());
File to = new File(dest.getCanonicalPath());
logger.debug("Berechne relativen Pfad von " + from + " zu " + to
+ ".\n");
if (from.equals(to)) {
return ".";
}
File file = to;
String downPath = "";
String upPath = "";
String relativePath;
String path1;
String path2;
String str;
File fromParent = from;
if (fromParent.isFile() == true) {
fromParent = fromParent.getParentFile();
}
while (fromParent != null) {
path1 = fromParent.getCanonicalPath() + File.separator;
path2 = to.getCanonicalPath();
logger.debug("path1 = " + path1);
logger.debug("path2 = " + path2);
if (path2.startsWith(path1)) {
str = StringServices.cutPrefix(path2, path1);
if (downPath.length() == 0) {
downPath = "." + File.separator;
}
str = appendPath(downPath, str);
relativePath = StringServices.chop(str, File.separator);
return relativePath;
}
downPath += ".." + File.separator;
if (file != null) {
upPath = file.getName() + File.separator + upPath;
}
fromParent = fromParent.getParentFile();
if (fromParent.getParent() == null) {
break;
}
if (file != null) {
file = file.getParentFile();
}
}
return dest.getCanonicalPath();
}
public static String removeParentPath(File dir, File parentDir)
throws IOException {
if (dir == null) {
throw new IllegalArgumentException(
"The argument dir must not be null!");
}
if (parentDir == null) {
throw new IllegalArgumentException(
"The argument parentDir must not be null!");
}
String parentPath = parentDir.getCanonicalPath();
if (parentPath.endsWith(Sfv.FSEP) == false) {
parentPath += Sfv.FSEP;
}
return removeParentPath(dir.getCanonicalPath(), parentPath);
}
public static String removeParentPath(String path, String parentPath) {
if (path == null) {
throw new IllegalArgumentException(
"The argument path must not be null!");
}
if (parentPath == null) {
throw new IllegalArgumentException(
"The argument parentPath must not be null!");
}
path = normalizePath(path);
parentPath = normalizePath(parentPath);
logger.debug("path=" + path);
logger.debug("parentPath=" + parentPath);
path = StringServices.cutPrefix(path, parentPath);
return path;
}
public static void rename(File srcFile, File destFile) throws IOException {
if (srcFile == null) {
throw new IllegalArgumentException(
"The argument srcFile must not be null!");
}
if (destFile == null) {
throw new IllegalArgumentException(
"The argument destFile must not be null!");
}
if (srcFile.equals(destFile)) {
logger.warn("Source file " + srcFile
+ " is identical to destination file.");
return;
}
boolean rc = srcFile.renameTo(destFile);
if (rc == true) {
return;
}
if (srcFile.isDirectory() == true) {
copyDir(srcFile, destFile);
delete(srcFile);
return;
}
throw new RenameFileException(srcFile, destFile);
}
/**
* Die Methode <code>replaceExtension</code> ersetzt die
* Dateinamenserweiterung.
*/
public static String replaceExtension(File file, String extension) {
return replaceExtension(file.getPath(), extension);
}
/**
* Die Methode <code>replaceExtension</code> ersetzt die
* Dateinamenserweiterung.
*/
public static String replaceExtension(String fileName, String extension) {
if (fileName == null) {
throw new IllegalArgumentException(
"The argument fileName must not be null!");
}
if (extension == null) {
throw new IllegalArgumentException(
"The argument extension must not be null!");
}
String base = getFileBase(fileName);
return base + extension;
}
public static boolean setReadOnly(File file) {
if (file == null || file.exists() == false) {
return false;
}
String[] cmd = null;
ExecResult result = null;
try {
if (JvmServices.isUnix()) {
if (file.isDirectory()) {
cmd = new String[7];
cmd[0] = "find";
cmd[1] = file.getCanonicalPath();
cmd[2] = "-exec";
cmd[3] = "chmod";
cmd[4] = "a-w";
cmd[5] = "{}";
cmd[6] = ";";
} else {
cmd = new String[3];
cmd[0] = "chmod";
cmd[1] = "a-w";
cmd[2] = file.getCanonicalPath();
}
}
if (JvmServices.isWindows()) {
cmd = new String[4];
cmd[0] = "attrib";
cmd[1] = "+r";
cmd[2] = "+h";
cmd[3] = file.getCanonicalPath();
if (file.isDirectory()) {
result = ExecServices.exec(cmd);
if (result.failed() == true) {
IOException oops = new IOException(result.toString());
throw oops;
}
cmd = new String[6];
cmd[0] = "attrib";
cmd[1] = "+r";
cmd[2] = "+h";
cmd[3] = file.getCanonicalPath() + "\\*.*";
cmd[4] = "/S";
cmd[5] = "/D";
}
}
if (cmd == null) {
logger.error("Operating System '"
+ JvmServices.getOperatingSystem()
+ "' is not supported!");
return false;
}
logger.debug("Executing command '"
+ StringServices.arrayToString(cmd) + "'...");
result = ExecServices.exec(cmd);
if (result.failed() == true) {
logger.error(result.toString());
return false;
}
} catch (IOException oops) {
logger.fatal(
"setReadOnly failed! (" + StringServices.arrayToString(cmd)
+ ")", oops);
return false;
}
return true;
}
public static boolean setReadOnly(String path) {
if (path == null) {
return false;
}
return setReadOnly(new File(path));
}
/**
* Die Methode <code>setWritable</code> setzt die Berechtigung Datei oder
* das Verzeichnis auf schreibbar. Falls eine Verzeichnis angegeben wurde,
* werden auch alle darin enthaltenen Dateien und Unterverzeichnisse
* bearbeitet.
*
* <code>setWritable</code> verwendet Kommandos des Betriebssystems um die
* Berechtigungen zu ändern. Unter Windows wird das Kommando
* <code>attrib</code> aufgerufen und zusätzlich das Attribut
* <code>hidden</code> zurückgesetzt.
*
* @param file
* <code>File</code>
*/
public static boolean setWritable(File file) {
if (file == null || file.exists() == false) {
return false;
}
String[] cmd = null;
ExecResult result = null;
try {
if (JvmServices.isUnix()) {
if (file.isDirectory()) {
cmd = new String[7];
cmd[0] = "find";
cmd[1] = file.getCanonicalPath();
cmd[2] = "-exec";
cmd[3] = "chmod";
cmd[4] = "a+w";
cmd[5] = "{}";
cmd[6] = ";";
} else {
cmd = new String[3];
cmd[0] = "chmod";
cmd[1] = "a+w";
cmd[2] = file.getCanonicalPath();
}
}
if (JvmServices.isWindows()) {
cmd = new String[4];
cmd[0] = "attrib";
cmd[1] = "-r";
cmd[2] = "-h";
cmd[3] = file.getCanonicalPath();
if (file.isDirectory()) {
result = ExecServices.exec(cmd);
if (result.failed() == true) {
IOException oops = new IOException(result.toString());
throw oops;
}
cmd = new String[6];
cmd[0] = "attrib";
cmd[1] = "-r";
cmd[2] = "-h";
cmd[3] = file.getCanonicalPath() + "\\*.*";
cmd[4] = "/S";
cmd[5] = "/D";
}
}
if (cmd == null) {
logger.error("Operating System '"
+ JvmServices.getOperatingSystem()
+ "' is not supported!");
return false;
}
logger.debug("Executing command '"
+ StringServices.arrayToString(cmd) + "'...");
result = ExecServices.exec(cmd);
if (result.failed() == true) {
logger.error(result.toString());
return false;
}
} catch (IOException oops) {
logger.fatal(
"setWritable failed! (" + StringServices.arrayToString(cmd)
+ ")", oops);
return false;
}
return true;
}
public static boolean setWritable(File file, String caller) {
logger.debug("Caller of setWritable is '" + caller + "'.");
return setWritable(file);
}
public static boolean setWritable(String path) {
if (path == null) {
return false;
}
return setWritable(new File(path));
}
public static boolean setWritable(String path, String caller) {
logger.debug("Caller of setWritable is '" + caller + "'.");
return setWritable(path);
}
public static void sort(File file) throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
Object[] array = readToArray(file);
Arrays.sort(array);
writeFromArray(file, array);
}
public static void touch(File file) throws IOException {
writeFromString(file, String.valueOf(System.currentTimeMillis()));
}
public static void touch(String fileName) throws IOException {
if (fileName == null) {
throw new IllegalArgumentException(
"The argument fileName must not be null!");
}
touch(new File(fileName));
}
public static String toWindowsPath(String path) {
if (path == null) {
throw new IllegalArgumentException(
"The argument path must not be null!");
}
String winPath = path;
Pattern winDrivePattern = Pattern.compile("^/[a-cA-Z]:/");
Matcher matcher = winDrivePattern.matcher(winPath);
if (matcher.lookingAt()) {
winPath = winPath.substring(1);
}
winPath = winPath.trim();
winPath = StringServices.replace(winPath, "/", "\\");
return winPath;
}
/**
* This method corrects the path regarding the used operating system.
* Windows "\" and Linux "/"
*
* @param in
* the string representing the path
* @return out the corrected string representing the path
*/
public static String correctPathSeperator(String in) {
String os = System.getProperty("os.name");
in = FileServices.normalizePath(in);
if (os.toLowerCase().contains("windows")) {
in = toWindowsPath(in);
return in;
}
return in;
}
public static void traverse(File dir, FileVisitor visitor) {
if (dir == null || dir.exists() == false || visitor == null) {
return;
}
for (File file : dir.listFiles()) {
visitor.visit(file);
}
File[] subdirs = dir.listFiles(new DirectoryFilter());
if (subdirs != null) {
for (File subdir : subdirs) {
traverse(subdir, visitor);
}
}
}
public static void write(File file, InputStream instr) throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
if (instr == null) {
throw new IllegalArgumentException(
"The argument instr must not be null!");
}
File parent = file.getParentFile();
if (parent != null) {
createPath(parent);
}
FileOutputStream out = new FileOutputStream(file);
int n = 0;
byte[] buffer = new byte[4096];
while ((n = instr.read(buffer, 0, 4096)) != -1) {
out.write(buffer, 0, n);
}
out.flush();
out.close();
}
public static void writeFromArray(File file, Object[] array)
throws IOException {
writeFromArray(file, array, "UTF-8");
}
public static void writeFromArray(File file, Object[] array, String encoding)
throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
if (array == null) {
throw new IllegalArgumentException(
"The argument array must not be null!");
}
if (encoding == null) {
throw new IllegalArgumentException(
"The argument encoding must not be null!");
}
PrintWriter writer = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(file), encoding));
try {
for (int i = 0; i < array.length; i++) {
writer.println(array[i]);
}
} finally {
writer.close();
}
}
public static void writeFromByteArray(File file, byte[] buffer)
throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
if (buffer == null) {
throw new IllegalArgumentException(
"The argument buffer must not be null!");
}
FileOutputStream out = new FileOutputStream(file);
out.write(buffer);
out.close();
}
public static void writeFromStream(String fileName, InputStream instr)
throws IOException {
if (fileName == null) {
throw new IllegalArgumentException(
"The argument fileName must not be null!");
}
if (instr == null) {
throw new IllegalArgumentException(
"The argument instr must not be null!");
}
FileOutputStream out = new FileOutputStream(fileName);
int n = 0;
byte[] buffer = new byte[4096];
while ((n = instr.read(buffer, 0, 4096)) != -1) {
out.write(buffer, 0, n);
}
out.close();
}
public static void writeFromString(File file, String str)
throws IOException {
writeFromString(file, str, "UTF-8");
}
/*
* Die Methode schreibt einen String in eine Datei
*
* @param File die Datei in die geschrieben wird
*
* @param String der zu schreibende String
*
* @param String die zu benutzende Zeichenkodierung (Standard UTF-8)
*/
public static void writeFromString(File file, String str, String encoding)
throws IOException {
if (file == null) {
throw new IllegalArgumentException(
"The argument file must not be null!");
}
File parent = file.getParentFile();
if (parent != null && parent.exists() == false) {
createPath(parent);
}
FileOutputStream fos = new FileOutputStream(file);
writeFromString(fos, str, encoding);
fos.close();
}
public static void writeFromString(OutputStream os, String str)
throws IOException {
writeFromString(os, str, "UTF-8");
}
public static void writeFromString(OutputStream os, String str,
String encoding) throws IOException {
if (os == null) {
throw new IllegalArgumentException(
"The argument os must not be null!");
}
if (str == null) {
throw new IllegalArgumentException(
"The argument str must not be null!");
}
if (encoding == null) {
throw new IllegalArgumentException(
"The argument encoding must not be null!");
}
PrintWriter writer = new PrintWriter(new OutputStreamWriter(os,
encoding));
try {
writer.print(str);
} finally {
writer.close();
}
}
public static void writeFromString(String fileName, String str)
throws IOException {
if (fileName == null) {
throw new IllegalArgumentException(
"The argument fileName must not be null!");
}
writeFromString(new File(fileName), str);
}
public static void writeFromString(String fileName, String str,
String encoding) throws IOException {
if (fileName == null) {
throw new IllegalArgumentException(
"The argument fileName must not be null!");
}
writeFromString(new File(fileName), str, encoding);
}
}
|