文件的各种操作工具类
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 | package zj.io.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.Reader; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import org.apache.commons.io.FileExistsException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; import org.apache.commons.io.monitor.FileAlterationMonitor; import org.apache.commons.io.monitor.FileAlterationObserver; import org.apache.commons.io.output.StringBuilderWriter; import org.apache.log4j.Logger; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import zj.check.util.CheckUtil; import zj.common.KV; import zj.common.VVV; import zj.common.exception.ServiceException; import zj.date.util.DateUtil; import zj.io.model.ICopyFilesCallBack; import zj.io.model.IJarCallBackRead; import zj.io.model.IJarCallBackWrite; import zj.io.model.JarCallBackRead; import zj.io.model.JarClass; import zj.io.model.JarParams; import zj.io.service.FileFilterI; import zj.io.service.IReadFilesCall; import zj.io.service.ReadLinesBatchCallI; import zj.io.service.ReadLinesCallI; /** * 类名 :FileUtil<br> * 概况 :文件工具类<br> * OutputStreamWriter/Reader->charsetName 一般情况下是:先打开的后关闭,后打开的先关闭 * * @version 1.00 (2011.12.02) * @author SHNKCS 张军 {@link <a target=_blank href=http://www.zhangjunbk.com>张军个人网站</a> <a target=_blank href=http://user.qzone.qq.com/360901061/>张军QQ空间</a>} */ public class FileUtil implements Serializable { private static final long serialVersionUID = 1L; /** 写文件换行标识 **/ // System.getProperty("line.separator").equals(FileUtil.LINE_SEPARATOR)->true public static String LINE_SEPARATOR; // = System.getProperty("line.separator"); /** 文件分割符:/,\\ **/ public static final String SEPARATOR = File.separator; private transient static final Logger logger = Logger.getLogger(FileUtil. class ); public static final int BUFSIZE = 8192 ; static { // avoid security issues StringBuilderWriter buf = new StringBuilderWriter( 4 ); PrintWriter out = new PrintWriter(buf); out.println(); LINE_SEPARATOR = buf.toString(); out.close(); } /** * 追加文件内容 * * @param file * 文件 * @param content * 内容 */ public final static void appendContentByFileWriter(File file, String content) { FileWriter fw = null ; PrintWriter pw = null ; try { fileMkdir(file); // 如果文件存在,则追加内容;如果文件不存在,则创建文件 fw = new FileWriter(file, true ); pw = new PrintWriter(fw); pw.println(content); pw.flush(); fw.flush(); } catch (Exception e) { throw new ServiceException(e); } finally { try { pw.close(); fw.close(); } catch (Exception e) { } } } /** * 追加文件内容 * * @param file * 文件 * @param content * 内容 */ public final static void appendContentByBufferedWriter(File file, String content) { BufferedWriter out = null ; try { out = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(file, true ))); out.write(content + FileUtil.LINE_SEPARATOR); out.flush(); } catch (Exception e) { throw new ServiceException(e); } finally { try { out.close(); } catch (Exception e) { } } } /** * 追加文件内容 * * @param file * 文件 * @param content * 内容 */ public final static void appendContentByRandomAccessFile(File file, String content) { RandomAccessFile raf = null ; try { // 打开一个随机访问文件流,按读写方式 raf = new RandomAccessFile(file.getAbsolutePath(), "rw" ); // 文件长度,字节数 long fileLength = raf.length(); // 将写文件指针移到文件尾。 raf.seek(fileLength); // raf.skipBytes(skipLength); raf.write((content + FileUtil.LINE_SEPARATOR).getBytes()); raf.close(); } catch (Exception e) { throw new ServiceException(e); } finally { try { raf.close(); } catch (Exception e) { } } } /** * 追加文件内容 * * @param file * 文件 * @param content * 内容 * @param before * 在前面 */ @Deprecated public final static void appendContentByRandomAccessFile(File file, String content, boolean before) { appendContentByRandomAccessFile(file, content, before ? 0 : Long.MAX_VALUE); } /** * 追加文件内容 * * @param file * 文件 * @param content * 内容 * @param skipLength * 在第几行写 */ @Deprecated public final static void appendContentByRandomAccessFile(File file, String content, long skipLength) { RandomAccessFile raf = null ; try { // 打开一个随机访问文件流,按读写方式 raf = new RandomAccessFile(file.getAbsolutePath(), "rw" ); // 文件长度,字节数 long fileLength = raf.length(); if (skipLength < 0 ) { skipLength = 0 ; } else if (skipLength == Long.MAX_VALUE) { skipLength = fileLength; } else { if (skipLength > fileLength) { skipLength = fileLength; } } // 将写文件指针移到文件尾。 raf.seek(skipLength); // raf.skipBytes(skipLength); raf.write((content + FileUtil.LINE_SEPARATOR).getBytes()); raf.close(); } catch (Exception e) { throw new ServiceException(e); } finally { try { raf.close(); } catch (Exception e) { } } } /** * 监听文件夹变化 * * @param rootDir * 文件夹路径 * @param adaptor * 监听文件适配器 */ public static void listenerFile( final String rootDir, final FileAlterationListenerAdaptor adaptor) { listenerFile(rootDir, adaptor, 1000 ); } /** * 监听文件夹变化 * * @param rootDir * 文件夹路径 * @param adaptor * 监听文件适配器 * @param interval * 轮询间隔 interval 秒 */ public static void listenerFile( final String rootDir, final FileAlterationListenerAdaptor adaptor, final long interval) { new Thread( new Runnable() { @Override public void run() { try { // logger.info("监听文件目录【" + rootDir + "】"); // 轮询间隔 1 秒 // long interval = TimeUnit.SECONDS.toMillis(1); // 创建一个文件观察器用于处理文件的格式 FileAlterationObserver observer = new FileAlterationObserver(rootDir); // 设置文件变化监听器 observer.addListener(adaptor); // 创建文件变化监听器 FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer); // 开始监控 monitor.start(); logger.info( "监听文件目录【" + rootDir + "】开始启动" ); } catch (Exception e) { logger.error( "监听出错" , e); } } }).start(); } /** * 拷贝文件 * * @param callBack * 拷贝回调 * */ public static void copyFiles(ICopyFilesCallBack callBack) { String input = callBack.getInputFile(); String output = callBack.getOutputFile(); try { // 拷贝文件路径[输入文件目录->拷贝文件路径] Collection<String> queryClass = callBack.getCopyFile(); File inputFile = new File(input); if (!inputFile.exists()) { throw new ServiceException( "输入文件目录不存在" ); } File outputFile = new File(output); if (!outputFile.exists()) { outputFile.mkdirs(); } // 查询所有源文件 List<File> files = new ArrayList<File>(); FileUtil.setFilterFiles(files, input); // classes路径前缀 String srcPrefix = "" ; input = FileUtil.linuxSeparator(input); if (!input.endsWith( "/" )) { input += "/" ; } // 源文件路径前缀 srcPrefix = input; // System.out.println("文件个数[" + files.size() + "]"); for (File inFile : files) { String lf = FileUtil.linuxSeparator(inFile.getAbsolutePath()); // 过虑后缀 // String includeExt = ".class"; // if (CheckUtil.isNotNull(includeExt) && !lf.endsWith(includeExt)) { // continue; // } // 取得类全路径com/xxx/xxx/xxx.class String clsPath = lf.substring(srcPrefix.length()); // System.out.println(lf + "###" + clsPath); if (queryClass.contains(clsPath)) { // 拷贝源class File outFile = new File(output, clsPath); // 判断目标文件目录是否存在 File dstFileDir = outFile.getParentFile(); if (!dstFileDir.exists()) { dstFileDir.mkdirs(); } FileUtil.copyFile(inFile, outFile); // 回调 callBack.copyFile(inFile, outFile); // System.out.println("源文件【" + inFile.getAbsolutePath() + "】拷贝到->【" + outFile.getAbsolutePath() + "】"); } } // System.out.println("文件个数[" + files.size() + "]"); } catch (Exception e) { throw new ServiceException(e); } } /** * 获取进程命令执行打印出来的信息 * * @param command * 命令 * @return */ public static List<String> cmdProcessInfo(String command) { return cmdProcessInfo(command, "GBK" ); } /** * 获取进程命令执行打印出来的信息 * * @param command * 命令 * @param charsetName * 编码 * @return */ public static List<String> cmdProcessInfo(String command, String charsetName) { List<String> lists = new ArrayList<String>(); BufferedReader in = null ; Process pro = null ; try { Runtime r = Runtime.getRuntime(); pro = r.exec(command); in = new BufferedReader( new InputStreamReader(pro.getInputStream(), charsetName)); String line = in.readLine(); line = IOUtils.readFirstLine(line); while (line != null ) { lists.add(line); line = in.readLine(); } } catch (Exception e) { throw new ServiceException(e); } finally { if (in != null ) { try { in.close(); } catch (IOException e) { } } if (pro != null ) { pro.destroy(); } } return lists; } /** * 创建文件目录 * * @param file * 文件/目录 */ public static void fileMkdir(File... files) { if (files == null ) return ; for (File file : files) { String outputDir = "" ; if (file.isDirectory()) { outputDir = file.getAbsolutePath(); } else { outputDir = file.getParent(); } File outputDirFile = new File(outputDir); if (!outputDirFile.exists()) { outputDirFile.mkdirs(); } } } /** * 拷贝文件 * * @param inputFile * 输入文件 * @param outputFile * 输出文件 */ public static void copyFile(File inputFile, File outputFile) { try { fileMkdir(outputFile); FileInputStream inputFIS = new FileInputStream(inputFile); FileOutputStream outputFOS = new FileOutputStream(outputFile); IOUtils.copyLarge(inputFIS, outputFOS); IOUtils.closeQuietly(inputFIS); IOUtils.closeQuietly(outputFOS); } catch (Exception e) { throw new ServiceException(e); } } /** * 读取jar包里面指定文件的内容 * * @param jarFilePath * jar包文件路径 * @param fileName * 文件路径名 * @throws IOException */ public static InputStream jarReadInputStream(String jarFilePath, String fileName) { JarFile jarFile = null ; try { jarFile = new JarFile(jarFilePath); JarEntry entry = jarFile.getJarEntry(fileName); InputStream is = jarFile.getInputStream(entry); return FileUtil.copyInputStream(is); } catch (Exception e) { throw new ServiceException(e); } finally { try { jarFile.close(); } catch (IOException e) { } } } /** * 读取回调jar文件 * * @param jarFile * jar包路径 * @param entryName * 要写的文件名 * @param data * 文件内容 * @throws Exception */ public static void jarRead(IJarCallBackRead call) { String jarFilePath = call.getFilePath(); if (CheckUtil.isNull(jarFilePath)) { throw new ServiceException( "文件路径zj.io.model.ICallBackWriteJar.getFilePath()不能为空" ); } // jar文件操作 JarFile jarFile = null ; try { // 1、首先将原Jar包里的所有内容读取到内存里,用TreeMap保存 jarFile = new JarFile(jarFilePath); // 读取jar包内容 Enumeration<JarEntry> es = jarFile.entries(); while (es.hasMoreElements()) { // 获取Jar对象 JarEntry je = es.nextElement(); // 文件名称 String name = je.getName(); // // 文件大小 // long size = je.getSize(); // // 压缩后的大小 // long compressedSize = je.getCompressedSize(); // 读取jar包字节 byte [] b = null ; try { b = FileUtil.readByteByStream(jarFile.getInputStream(je)); } catch (Exception e) { b = null ; } // 放入临时集合中 boolean isContinue = call.read(je, KV.with(name, b)); if (!isContinue) { // 中断 break ; } } } catch (Exception e) { throw new ServiceException(e); } finally { try { jarFile.close(); } catch (IOException e) { } } } /** * 读取jar文件内容到map中 * * @param filePath * jar包路径 * @throws Exception */ public static Map<String, byte []> jarReadToMap( final String filePath) { // 可以保持排列的顺序,所以用TreeMap 而不用HashMap final Map<String, byte []> tm = new TreeMap<String, byte []>(); jarRead( new JarCallBackRead() { @Override public String getFilePath() { return filePath; } @Override public boolean read(JarEntry je, KV<String, byte []> kv) { tm.put(kv.getK(), kv.getV()); return true ; } }); return tm; } /** * 修改Jar包里的文件或者添加文件 * * @param call * {@code jarFile jar包路径,entryName 要写的文件名,data 文件内容} * @throws Exception */ public static void jarWrite(IJarCallBackWrite call) { String filePath = call.getFilePath(); // 可以保持排列的顺序,所以用TreeMap 而不用HashMap Map<String, byte []> tm = jarReadToMap(filePath); String newFilePath = call.getNewFilePath(); if (CheckUtil.isNull(newFilePath)) { newFilePath = filePath; } String entryName = call.getEntryName(); byte [] data = call.getEntryData(); boolean override = call.getEntryOverride(); // jar文件操作 JarFile jarFile = null ; JarOutputStream jos = null ; FileOutputStream fos = null ; try { // 1、首先将原Jar包里的所有内容读取到内存里,用TreeMap保存 jarFile = new JarFile(filePath); // 写出jar文件 fos = new FileOutputStream(newFilePath); // 创建jar输出流 jos = new JarOutputStream(fos); Iterator<Map.Entry<String, byte []>> it = tm.entrySet().iterator(); // 判断是否添加新的文件 boolean isExistFile = false ; // 2、将TreeMap重新写到原jar里,如果TreeMap里已经有entryName文件那么覆盖,否则在最后添加 while (it.hasNext()) { Map.Entry<String, byte []> item = it.next(); // 当前文件名 String name = item.getKey(); // 当前文件字节码 byte [] tempData = item.getValue(); if (name.equals(entryName)) { // 如果数据存在,不能执行下面添加操作,覆盖,名称相同 isExistFile = true ; if (data != null && override) { // 覆盖文件 tempData = data; } } // 回调操作 VVV<Boolean, String, byte []> result = call.updateData(KV.with(name, tempData)); if (result != null ) { if (!result.getV1()) { // 删除此文件 continue ; } // 重新赋值名称和数据 name = result.getV2(); tempData = result.getV3(); } // 实例化jar里的对象 JarEntry entry = new JarEntry(name); // 放入jar文件中 jos.putNextEntry(entry); // 写入字节 jos.write(tempData, 0 , tempData.length); } if (CheckUtil.isNotNull(entryName) && !isExistFile) { // 如果不存在文件则添加 // 最后添加 JarEntry newEntry = new JarEntry(entryName); jos.putNextEntry(newEntry); jos.write(data, 0 , data.length); } jos.finish(); } catch (Exception e) { throw new ServiceException(e); } finally { try { fos.close(); } catch (IOException e) { } try { jos.close(); } catch (IOException e) { } try { jarFile.close(); } catch (IOException e) { } } } /** * 深度拷贝流 * * @param is * 深度拷贝流 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @throws IOException */ public static InputStream copyInputStream(InputStream is) { try { // 创建一个新的流 return new ByteArrayInputStream(readByteByStream(is)); } catch (Exception e) { throw new ServiceException(e); } } /** * 按行输出流内容 * * @param is * 流,此is不关闭 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @throws IOException */ public static void printInputStream(InputStream is) { printInputStream(is, "GBK" ); } /** * 按行输出流内容 * * @param is * 流,此is不关闭 * @param charsetName * 字符集 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @throws IOException */ public static void printInputStream(InputStream is, String charsetName) { BufferedReader reader = null ; InputStreamReader isr = null ; try { isr = new InputStreamReader(is, charsetName); reader = new BufferedReader(isr); String line = null ; while ((line = reader.readLine()) != null ) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(reader); } } /** * 读取流 * * @param file * 文件 * @return 字节数组 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @return 字节流 * @throws Exception */ public static byte [] readByteByFile(File file) { try { return readByteByStream( new FileInputStream(file)); } catch (IOException e) { throw new ServiceException(e); } } /** * 读取流 * * @param is * 输入流 * @return 字节数组 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @return 字节流 * @throws Exception */ public static byte [] readByteByStream(InputStream is) { ByteArrayOutputStream baos = null ; try { baos = new ByteArrayOutputStream(); byte [] buff = new byte [BUFSIZE]; int len = - 1 ; while ((len = is.read(buff)) != - 1 ) { baos.write(buff, 0 , len); } byte [] b = baos.toByteArray(); return b; } catch (Exception e) { throw new ServiceException(e); } finally { IOUtils.closeQuietly(baos); IOUtils.closeQuietly(is); } } /** * 设置文件目录/文件的修改时间 * * @param file * 文件 * @param lmdate * 修改的日期 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @return */ public static void setLastModified(File file, String lmdate) { if (file == null || !file.exists()) { logger.warn( "文件不存在,无法设置修改时间" ); return ; } Date ld = DateUtil.parseDate(lmdate); if (ld == null ) { logger.warn( "日期格式不正确" ); return ; } long lastDate = ld.getTime(); if (file.isDirectory()) { // 读取文件目录 List<File> files = new ArrayList<File>(); FileUtil.setFilterFiles(files, file.getAbsolutePath()); for (File $file : files) { $file.setLastModified(lastDate); } } else { file.setLastModified(lastDate); } } /** * 移动文件 * * @param srcFile * 源文件 * @param destFile * 目标文件(文件或目录) * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @return */ public static void moveFile(File srcFile, File destFile) throws Exception { moveFile(srcFile, destFile, false ); } /** * 移动文件 * * @param srcFile * 源文件 * @param destFile * 目标文件(文件或目录) * @param overrideFile * 是否覆盖 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @return */ public static void moveFile(File srcFile, File destFile, boolean overrideFile) throws Exception { // File srcFile = new File("D:/msth/ipo/excel/入围/复核/复核-20161103.xlsx"); // File destFile = new File("D:/msth/ipo/excel/入围/复核/backup"); // boolean overrideFile = false; try { if (overrideFile) { // 拷贝文件 if (destFile.isDirectory()) { try { FileUtils.copyFileToDirectory(srcFile, destFile); } catch (Exception e1) { // 不做处理 } } else { try { FileUtils.copyFile(srcFile, destFile); } catch (Exception e1) { // 不做处理 } } // 删除源文件 srcFile.delete(); } else { if (destFile.isDirectory()) { FileUtils.moveFileToDirectory(srcFile, destFile, true ); } else { FileUtils.moveFile(srcFile, destFile); } } } catch (Exception e) { if (e instanceof FileExistsException) { // 文件存在 if (destFile.isDirectory()) { String destPath = srcFile.getAbsolutePath(); File renameDestFile = new File(destFile, FilenameUtils.getBaseName(destPath) + "-" + DateUtil.dateParse( new Date(), "yyyyMMddHHmmssSSS" ) + "." + FilenameUtils.getExtension(destPath)); FileUtils.moveFile(srcFile, renameDestFile); } else { String destPath = destFile.getAbsolutePath(); File renameDestFile = new File(FilenameUtils.getBaseName(destPath) + "-" + DateUtil.dateParse( new Date(), "yyyyMMddHHmmssSSS" ) + "." + FilenameUtils.getExtension(destPath)); FileUtils.moveFile(srcFile, renameDestFile); } } else { e.printStackTrace(); throw e; } } } /** * 取得文件的创建时间 * * @param file * @return */ public static final String getCreateTime(File file) { String createTime = "" ; try { Process p = Runtime.getRuntime().exec( "cmd /C dir " + file.getAbsolutePath() + " /tc" ); InputStream is = p.getInputStream(); // ant下的zip工具默认压缩编码为UTF-8编码, 而winRAR软件压缩是用的windows默认的GBK或者GB2312编码 所以解压缩时要制定编码格式 BufferedReader br = new BufferedReader( new InputStreamReader(is, "gbk" )); String line = null ; int i = 0 ; while ((line = br.readLine()) != null ) { if (++i == 6 ) { createTime = line.substring( 0 , 17 ); } } } catch (Exception e) { createTime = "" ; logger.error(e.getMessage()); } return createTime; } /** * 根据系统改变路径分割符号 * * @param path * 路径 * @param isSpeEnd * 是否添加最后分割符 * <p> * true:添加 * </p> * <p> * false:默认 * </p> * @see #changePathSeparator(String, zj.io.util.ConstantForEnum.ChangePathLastSeparator) * @return 改变后的系统路径 */ @Deprecated public static final String changePathSeparator(String path, boolean isSpeEnd) { if (CheckUtil.isNull(path)) return "" ; // logger.debug("改变路径分割符号前path:" + path); if (SEPARATOR.equals( "/" )) { // 非windows系统 path = path.replaceAll( "\\\\" , "/" ); if (isSpeEnd) { if (!path.endsWith( "/" )) { path = path + "/" ; } } } else { // windows系统 path = path.replaceAll( "/" , "\\\\" ); if (isSpeEnd) { if (!path.endsWith( "\\" )) { path = path + "\\" ; } } } return path; } /** * 根据系统改变路径分割符号 * * @param path * 路径 * @param sepEnum * 常量枚举{@link zj.io.util.ConstantForEnum.ChangePathLastSeparator} * @return 改变后的系统路径 */ public static final String changePathSeparator(String path, ConstantForEnum.ChangePathLastSeparator sepEnum) { if (CheckUtil.isNull(path)) return "" ; // logger.debug("改变路径分割符号前path:" + path); if (SEPARATOR.equals( "/" )) { path = linuxSeparator(path, sepEnum); } else { path = windowsSeparator(path, sepEnum); } return path; } /** * 根据系统改变包路径分割符号 * * @param packagePath * 包路径 * @return 包路径 */ public static final String packageToPath(String packagePath) { if (CheckUtil.isNull(packagePath)) return "" ; // logger.debug("改变路径分割符号前path:" + path); if (SEPARATOR.equals( "/" )) { packagePath = packagePath.replaceAll( "\\." , "/" ); } else { packagePath = packagePath.replaceAll( "\\." , "\\\\" ); } return packagePath; } /** * window分割符 * * @param path * 路径 * @return 改变后的系统路径 */ public static final String windowsSeparator(String path) { return windowsSeparator(path, ConstantForEnum.ChangePathLastSeparator.NONE); } /** * window分割符 * * @param path * 路径 * @param sepEnum * 常量枚举{@link zj.io.util.ConstantForEnum.ChangePathLastSeparator} * @return 改变后的系统路径 */ public static final String windowsSeparator(String path, ConstantForEnum.ChangePathLastSeparator sepEnum) { if (CheckUtil.isNull(path)) return "" ; // windows系统 path = path.replaceAll( "/" , "\\\\" ); if (ConstantForEnum.ChangePathLastSeparator.ADD_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.ADD_BEFORE == sepEnum) { if (!path.startsWith( "\\" )) { path = "\\" + path; } } if (ConstantForEnum.ChangePathLastSeparator.ADD_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.ADD_AFTER == sepEnum) { if (!path.endsWith( "\\" )) { path = path + "\\" ; } } if (ConstantForEnum.ChangePathLastSeparator.DEL_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.DEL_BEFORE == sepEnum) { if (path.startsWith( "\\" )) { path = path.substring( 1 ); } } if (ConstantForEnum.ChangePathLastSeparator.DEL_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.DEL_AFTER == sepEnum) { if (path.endsWith( "\\" )) { path = path.substring( 0 , path.length() - 1 ); } } return path; } /** * linux分割符 * * @param path * 路径 * @return 改变后的系统路径 */ public static final String linuxSeparator(String path) { return linuxSeparator(path, ConstantForEnum.ChangePathLastSeparator.NONE); } /** * linux分割符 * * @param path * 路径 * @param sepEnum * 常量枚举{@link zj.io.util.ConstantForEnum.ChangePathLastSeparator} * @return 改变后的系统路径 */ public static final String linuxSeparator(String path, ConstantForEnum.ChangePathLastSeparator sepEnum) { if (CheckUtil.isNull(path)) return "" ; // 非windows系统 path = path.replaceAll( "\\\\" , "/" ); // switch (sepEnum) { // case ADD_ALL: // case ADD_BEFORE: // break; // case ADD_AFTER: // break; // default: // break; // } if (ConstantForEnum.ChangePathLastSeparator.ADD_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.ADD_BEFORE == sepEnum) { if (!path.startsWith( "/" )) { path = "/" + path; } } if (ConstantForEnum.ChangePathLastSeparator.ADD_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.ADD_AFTER == sepEnum) { if (!path.endsWith( "/" )) { path = path + "/" ; } } if (ConstantForEnum.ChangePathLastSeparator.DEL_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.DEL_BEFORE == sepEnum) { if (path.startsWith( "/" )) { path = path.substring( 1 ); } } if (ConstantForEnum.ChangePathLastSeparator.DEL_ALL == sepEnum || ConstantForEnum.ChangePathLastSeparator.DEL_AFTER == sepEnum) { if (path.endsWith( "/" )) { path = path.substring( 0 , path.length() - 1 ); } } return path; } /** * 根据系统改变路径分割符号 * * @param path * @return */ public static final String changePathSeparator(String path) { return changePathSeparator(path, ConstantForEnum.ChangePathLastSeparator.NONE); } /** * 获得文件扩展名及前面的字符串 * * @param filePath * E:\\xmls\\iqc_basic_user.xml [E:\xmls\,iqc_basic_user,.xml,false] * @return */ public static final String[] getFileNameExtension(String filePath) { String[] rtnStrs = new String[ 4 ]; rtnStrs[ 0 ] = "" ; rtnStrs[ 1 ] = "" ; rtnStrs[ 2 ] = "" ; rtnStrs[ 3 ] = "" ; String dirPath = "" ; String fileName = "" ; String fileExtension = "" ; String tempStr = "" ; int index = - 1 ; filePath = changePathSeparator(filePath); if (CheckUtil.isNotNull(filePath)) { index = filePath.lastIndexOf(SEPARATOR); if (index >= 0 ) { dirPath = filePath.substring( 0 , index + 1 ); tempStr = filePath.substring(index + 1 ); index = tempStr.lastIndexOf( "." ); if (index >= 0 ) { fileName = tempStr.substring( 0 , index); fileExtension = tempStr.substring(index); } } else { index = filePath.lastIndexOf( "." ); if (index >= 0 ) { fileName = filePath.substring( 0 , index); dirPath = fileName; fileExtension = filePath.substring(index); } else { dirPath = filePath; fileName = filePath; } } } rtnStrs[ 0 ] = dirPath; rtnStrs[ 1 ] = fileName; rtnStrs[ 2 ] = fileExtension; String diskPath = "" ; try { diskPath = dirPath.substring(dirPath.indexOf( "\\" ) + 1 ); } catch (Exception e) { diskPath = "" ; } if ( "" .equals(diskPath)) { rtnStrs[ 3 ] = "true" ; } else { rtnStrs[ 3 ] = "false" ; } return rtnStrs; } /** * 获取图片流 * * @param file * @return * @throws IOException */ public static final ImageReader getImageReader(File file) { try { ImageReader reader = null ; String fileExtension = FilenameUtils.getExtension(file.getName()); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(fileExtension); reader = readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(file); reader.setInput(iis, true ); return reader; } catch (Exception e) { throw new ServiceException(e); } } /** * 创建文件或目录 * * @param file * 文件对象 * @param isFolder * 是否是目录 * @return 创建是否成功 * @throws IOException */ public static final boolean createFolderOrFile(File file, boolean isFolder) { if (file == null ) return false ; if (isFolder) { if (file.exists()) { if (file.isFile()) { logger.warn( "创建文件夹失败:将要创建的文件【" + file.getAbsolutePath() + "】重名" ); } else if (file.isDirectory()) { logger.warn( "创建文件夹失败:将要创建的文件夹【" + file.getAbsolutePath() + "】已经存在" ); } return false ; } else { file.mkdirs(); logger.debug( "创建文件夹【" + file.getAbsolutePath() + "】成功!" ); return true ; } } else { String path = file.getPath(); String[] tempPaths = getFileNameExtension(path); File fileDir = new File(tempPaths[ 0 ]); if (fileDir.exists()) { logger.warn( "创建文件夹失败:将要创建的文件夹【" + fileDir.getAbsolutePath() + "】已经存在" ); return false ; } else { fileDir.mkdirs(); logger.debug( "创建文件夹【" + fileDir.getAbsolutePath() + "】成功!" ); return true ; } } } /** * 创建文件或目录 * * @param file * @return * @throws IOException */ public static final boolean createFolderOrFile(String file) { return createFolderOrFile(file, false ); } /** * 创建文件或目录 * * @param file * @param isFolder * @return * @throws IOException */ public static final boolean createFolderOrFile(String file, boolean isFolder) { if (CheckUtil.isNull(file)) { return false ; } file = changePathSeparator(file); return createFolderOrFile( new File(file), isFolder); } /** * 创建文件 * * @param file * @throws IOException */ public static final void forceMkdirFolderOrFile(String file) { if (CheckUtil.isNull(file)) { return ; } file = changePathSeparator(file); forceMkdirFolderOrFile( new File(file)); } /** * 创建文件或目录 * * @param file * 文件对象 * @throws IOException */ public static final void forceMkdirFolderOrFile(File file) { try { if (file == null ) return ; if (!file.exists()) { // 创建目录 if (file.isFile()) { String path = file.getPath(); String[] tempPaths = getFileNameExtension(path); File fileDir = new File(tempPaths[ 0 ]); if (fileDir.exists()) { logger.warn( "创建文件夹失败:将要创建的文件夹【" + fileDir.getAbsolutePath() + "】已经存在" ); } else { fileDir.mkdirs(); logger.debug( "创建文件夹【" + fileDir.getAbsolutePath() + "】成功!" ); } } else { file.mkdirs(); logger.debug( "创建文件夹【" + file.getAbsolutePath() + "】成功!" ); } } if (file.isFile()) { file.createNewFile(); logger.debug( "创建文件【" + file.getAbsolutePath() + "】成功!" ); } } catch (Exception e) { logger.error(e); } } /** * 创建目录 * * @param file * @return * @throws IOException */ public static final boolean createFolderOrFile(File file) { return createFolderOrFile(file, false ); } /** * 将一个字符串转化为输入流 * * @param sInputString * @return */ public static final InputStream getStringStream(String sInputString) { return getStringStream(sInputString, "utf-8" ); } /** * 将一个字符串转化为输入流 * * @param sInputString * @param charset * @return */ public static final InputStream getStringStream(String sInputString, String charset) { if (sInputString != null && !sInputString.trim().equals( "" )) { try { ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes(charset)); return tInputStringStream; } catch (Exception ex) { ex.printStackTrace(); } } return null ; } /** * 将一个输入流转化为字符串 * * @see #readString(File) * @param file * 文件对象 * @return */ @Deprecated public static final String getStreamString(File file) { try { return getStreamString( new BufferedInputStream( new FileInputStream(file))); } catch (Exception e) { throw new ServiceException(e); } } /** * 将一个输入流转化为字符串 * * @see #readString(InputStream, boolean) * @param is * 输入流 * @return 文件内容 */ public static final String getStreamString(InputStream is) { InputStreamReader isr = null ; if (is != null ) { StringBuffer sb = new StringBuffer(); BufferedReader br = null ; try { br = new BufferedReader((isr = new InputStreamReader(is))); String sLine = null ; sLine = br.readLine(); sLine = IOUtils.readFirstLine(sLine); if (sLine != null ) { sb.append(sLine); while ((sLine = br.readLine()) != null ) { sb.append(sLine); } } return sb.toString(); } catch (Exception e) { throw new ServiceException(e); } finally { try { if (br != null ) br.close(); } catch (Exception e) { e.printStackTrace(); } try { if (isr != null ) isr.close(); } catch (Exception e) { e.printStackTrace(); } try { if (is != null ) is.close(); } catch (Exception e) { e.printStackTrace(); } } } return null ; } /** * 设置一个目录的所有文件至集合中 * * @param fileList * 过虑后的文件集合 * @param dir * 目录 * @param filter * 自定义文件过虑器 * @param defaultFilter * 默认过虑器 */ public static final void setFilterFilesLevel(List<File> fileList, String dir, FileFilterI filter, FileFilter defaultFilter, int level) { File file = new File(dir); if (!file.exists()) { logger.warn( "文件:" + file.getAbsolutePath() + "不存在" ); return ; } if (filter == null ) { // 自定义filter为空 if (file.isDirectory()) { File[] files = null ; if (defaultFilter == null ) { files = file.listFiles(); } else { files = file.listFiles(defaultFilter); } if (files == null ) { logger.debug( "文件:" + file.getAbsolutePath() + "不存在" ); } else { for (File info : files) { if (info.isDirectory()) { fileList.add(info); setFilterFilesLevel(fileList, info.getPath(), filter, defaultFilter, 0 ); } else { // 如果是文件 fileList.add(info); } } } } else { fileList.add(file); } } else { int tempLevel = level + 1 ; if (file.isDirectory()) { // 如果是目录 if (filter.interrupt(file, fileList)) { logger.debug( "待判断文件夹:" + file.getAbsolutePath() + "退出" ); return ; } File[] files = null ; if (defaultFilter == null ) { files = file.listFiles(); } else { files = file.listFiles(defaultFilter); } if (files == null ) { logger.debug( "文件:" + file.getAbsolutePath() + "不存在" ); } else { for (File info : files) { if (level == 0 ) { // 如果当前是开始目录,则设置为1 tempLevel = 1 ; } filter.setLevel(tempLevel); if (filter.accept(info)) { // 是否接收文件夹或文件 if (info.isDirectory()) { if (filter.acceptDir(info)) { // 是否接收文件夹 if (filter.interrupt(info, fileList)) { logger.debug( "循环中待添加文件夹:" + info.getAbsolutePath() + "中断" ); break ; } fileList.add(info); } if (filter.interrupt(info, fileList)) { logger.debug( "待回调文件夹:" + info.getAbsolutePath() + "中断" ); break ; } setFilterFilesLevel(fileList, info.getPath(), filter, defaultFilter, tempLevel); } else { // 如果是文件 if (filter.acceptFile(info)) { // 是否接受文件 if (filter.interrupt(info, fileList)) { logger.debug( "循环中待添加文件:" + info.getAbsolutePath() + "中断" ); break ; } fileList.add(info); } } } } } } else { // 设置当前文件级别 filter.setLevel(tempLevel); if (filter.accept(file)) { if (filter.interrupt(file, fileList)) { logger.debug( "待判断文件:" + file.getAbsolutePath() + "退出" ); return ; } if (filter.acceptFile(file)) { if (filter.interrupt(file, fileList)) { logger.debug( "待添加文件:" + file.getAbsolutePath() + "中断" ); return ; } fileList.add(file); } } } } } /** * 读取某个文件夹下的所有文件 * * @param inpath * 输入目录 * @param call * 读取文件回调接口 */ public static void readFiles(File file, IReadFilesCall call) { try { if (call == null ) { // 如果无实现,则退出 return ; } if (call.isInterrupt()) { return ; } if (file.isDirectory()) { // 文件列表信息 File[] filelist = file.listFiles(); // 循环文件列表 for (File thisFile : filelist) { if (thisFile.isDirectory()) { // 如果是目录 // 每个文件回调 call.callback(file); // 目录回调 call.directory(thisFile); // 递归调用 readFiles(thisFile, call); } else { // 如果是文件 // 每个文件回调 call.callback(thisFile); // 文件回调 call.file(thisFile); } } } else { // 每个文件回调 call.callback(file); // 文件回调 call.file(file); } } catch (Exception e) { logger.error(e); } } /** * 设置一个目录的所有文件至集合中 * * @param fileList * 过虑后的文件集合 * @param dir * 目录 * @param filter * 自定义文件过虑器 * @param defaultFilter * 默认过虑器 */ public static final void setFilterFiles(List<File> fileList, String dir, FileFilterI filter, FileFilter defaultFilter) { setFilterFilesLevel(fileList, dir, filter, defaultFilter, 0 ); } /** * 设置一个目录的所有文件至集合中 * * @param fileList * 过虑后的文件集合 * @param dir * 目录 * @param defaultFilter * 默认过虑器 */ public static final void setFilterFiles(List<File> fileList, String dir, FileFilter defaultFilter) { setFilterFiles(fileList, dir, null , defaultFilter); } /** * 设置一个目录的所有文件至集合中 * * @param fileList * 过虑后的文件集合 * @param dir * 目录 * @param filter * 自定义文件过虑器 */ public static final void setFilterFiles(List<File> fileList, String dir, FileFilterI filter) { setFilterFiles(fileList, dir, filter, null ); } /** * 设置一个目录的所有文件至集合中 * * @param fileList * 过虑后的文件集合 * @param dir * 目录 */ public static final void setFilterFiles(List<File> fileList, String dir) { setFilterFiles(fileList, dir, null , null ); } /** * 设置属性文件的值 * * @param path * @param key * @param value * @throws Exception */ public static final void setProperty(String path, String key, String value) throws Exception { FileInputStream fis = new FileInputStream(path); BufferedInputStream bis = new BufferedInputStream(fis); // 配置文件内容解析 Properties prop = new Properties(); prop.load(bis); bis.close(); fis.close(); FileOutputStream fos = new FileOutputStream(path); BufferedOutputStream bos = new BufferedOutputStream(fos); // Properties prop = getProperties(path); prop.setProperty(key, value); prop.store(bos, null ); bos.flush(); fos.flush(); bos.close(); fos.close(); } /** * 获取属性值 * * @param path * @param key * @return * @throws Exception */ public static final String getProperty(String path, String key) throws Exception { return getProperties(path).getProperty(key); } /** * 获取属性对象 * * @param path * @param key * @return * @throws Exception */ public static final Properties getProperties(String path) throws Exception { FileInputStream fis = new FileInputStream(path); BufferedInputStream bis = new BufferedInputStream(fis); // 配置文件内容解析 Properties prop = new Properties(); prop.load(bis); bis.close(); fis.close(); return prop; } /** * 将对象序列化到磁盘文件中 * * @param t * 对象 * @param filePath * 文件路径 * @throws Exception */ public static final <T> void writeObjectToFile(T t, String filePath) throws Exception { writeObjectToFile(t, new File(filePath)); } /** * 将对象序列化到磁盘文件中 * * @param t * @param file * @throws Exception */ public static final <T> void writeObjectToFile(T t, File file) throws Exception { FileOutputStream fos = null ; BufferedOutputStream bos = null ; ObjectOutputStream oos = null ; try { String[] fileExts = getFileNameExtension(file.getAbsolutePath()); String newFilePath = "" ; if (fileExts.length > 0 ) { newFilePath += fileExts[ 0 ]; } File extFileDir = new File(newFilePath); if (!extFileDir.exists()) { extFileDir.mkdirs(); } if (fileExts.length > 1 ) { newFilePath += fileExts[ 1 ]; } if (fileExts.length > 2 ) { newFilePath += fileExts[ 2 ]; } file = new File(newFilePath); if (file.exists()) { file.delete(); } fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); oos = new ObjectOutputStream(bos); oos.writeObject(t); oos.flush(); } finally { try { if (oos != null ) { oos.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (bos != null ) { bos.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (fos != null ) { fos.close(); } } catch (Exception e) { e.printStackTrace(); } } } /** * 反序列化,将字符串转化为对象 * * @param serStr * @return * @throws Exception */ public static final <T> T readStrToObject(String serStr) throws Exception { return readStrToObject(serStr, "UTF-8" ); } /** * 反序列化,将字符串转化为对象 * * @param serStr * @param charsetName * @return * @throws Exception */ @SuppressWarnings ( "unchecked" ) public static final <T> T readStrToObject(String serStr, String charsetName) throws Exception { if (CheckUtil.isNull(serStr)) return null ; T obj = null ; ObjectInputStream ois = null ; ByteArrayInputStream bais = null ; try { String redStr = "" ; redStr = java.net.URLDecoder.decode(serStr, charsetName); bais = new ByteArrayInputStream(redStr.getBytes( "ISO-8859-1" )); ois = new ObjectInputStream(bais); obj = (T) ois.readObject(); } finally { try { if (ois != null ) { ois.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (bais != null ) { bais.close(); } } catch (Exception e) { e.printStackTrace(); } } return obj; } // //序列化对象为String字符串,先对序列化后的结果进行BASE64编码,否则不能直接进行反序列化 // public static final String writeObject(Object o) throws Exception { // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // ObjectOutputStream oos = new ObjectOutputStream(bos); // oos.writeObject(o); // oos.flush(); // oos.close(); // bos.close(); // //return new BASE64Encoder().encode(bos.toByteArray()); // return new String(bos.toByteArray(), "ISO-8859-1"); // } // // //反序列化String字符串为对象 // // public static final Object readObject(String object) throws Exception{ // //ByteArrayInputStream bis = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(object)); // ByteArrayInputStream bis = new ByteArrayInputStream(object.getBytes("ISO-8859-1")); // ObjectInputStream ois = new ObjectInputStream(bis); // Object o = null; // try { // o = ois.readObject(); // } catch(EOFException e) { // System.err.print("read finished"); // } // bis.close(); // ois.close(); // return o; // } /** * 将对象序列化成字符串 * * @param t * @return * @throws Exception */ public static final <T> String writeObjectToStr(T t) throws Exception { if (t == null ) return null ; ByteArrayOutputStream baos = null ; ObjectOutputStream oos = null ; String serStr = null ; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(t); oos.flush(); baos.flush(); serStr = baos.toString( "ISO-8859-1" ); serStr = java.net.URLEncoder.encode(serStr, "UTF-8" ); } finally { oos.close(); baos.close(); } return serStr == null ? "" : serStr; } /** * 反序列化,将磁盘文件转化为对象 * * @param filePath * 文件路径 * @return * @throws Exception */ public static final <T> T readFileToObject(String filePath) throws Exception { if (filePath == null || filePath.trim().equals( "" )) return null ; File file = new File(filePath); return readFileToObject(file); } /** * 反序列化,将磁盘文件转化为对象 * * @param file * 文件对象 * @return * @throws Exception */ @SuppressWarnings ( "unchecked" ) public static final <T> T readFileToObject(File file) throws Exception { FileInputStream fis = null ; BufferedInputStream bis = null ; ObjectInputStream ois = null ; T obj = null ; try { if (!file.exists()) return null ; fis = new FileInputStream(file); bis = new BufferedInputStream(fis); ois = new ObjectInputStream(bis); obj = (T) ois.readObject(); } finally { ois.close(); bis.close(); fis.close(); } return obj; } // readLinesCount // ----------------------------------------------------------------------- public static final long readLinesCount(File file) { return readLinesCount(file, null ); } public static final long readLinesCount(File file, String encoding) { InputStream in = null ; try { in = FileUtils.openInputStream(file); return readLinesCount(in, encoding); } catch (Exception e) { throw new ServiceException(e); } finally { IOUtils.closeQuietly(in); } } public static final long readLinesCount(InputStream input, String encoding) { try { if (encoding == null ) { return readLinesCount(input); } else { InputStreamReader reader = new InputStreamReader(input, encoding); return readLinesCount(reader); } } catch (Exception e) { throw new ServiceException(e); } } public static final long readLinesCount(InputStream input) { InputStreamReader reader = new InputStreamReader(input); return readLinesCount(reader); } public static final long readLinesCount(Reader input) { try { long lineNum = 0 ; BufferedReader reader = new BufferedReader(input); String line = reader.readLine(); line = IOUtils.readFirstLine(line); while (line != null ) { lineNum++; line = reader.readLine(); } return lineNum; } catch (Exception e) { throw new ServiceException(e); } } // readString /** * 读取文件内容 * * @param file * 文件对象 * @param line * 是否换行(true:换行,false:非换行),默认换行 * @return 文件内容 * @throws IOException */ public static final String readString(File file) { return readString(file, true ); } /** * 读取文件内容 * * @param file * 文件对象 * @param line * 是否换行(true:换行,false:非换行) * @return 文件内容 * @throws IOException */ public static final String readString(File file, boolean line) { return readString(file, null , line); } /** * 读取文件内容 * * @param file * 文件对象 * @param encoding * 编码 * @return 文件内容 * @throws IOException */ public static final String readString(File file, String encoding) { return readString(file, encoding, true ); } /** * 读取文件内容 * * @param file * 文件对象 * @param encoding * 编码 * @param line * 是否换行(true:换行,false:非换行) * @return 文件内容 * @throws IOException */ public static final String readString(File file, String encoding, boolean line) { InputStream in = null ; try { in = FileUtils.openInputStream(file); return readString(in, encoding, line); } catch (Exception e) { throw new ServiceException(e); } finally { IOUtils.closeQuietly(in); } } /** * 读取文件内容 * * @param input * 输入流 * @param encoding * 编码 * @param line * 是否换行(true:换行,false:非换行) * @return 文件内容 * @throws IOException */ public static final String readString(InputStream input, String encoding, boolean line) { InputStreamReader reader = null ; try { if (CheckUtil.isNull(encoding)) { encoding = "UTF-8" ; } // if (encoding == null) { // return readString(input, line); // } else { // reader = new InputStreamReader(input, encoding); // return readString(reader, line); // } reader = new InputStreamReader(input, encoding); return readString(reader, line); } catch (Exception e) { throw new ServiceException(e); } finally { IOUtils.closeQuietly(reader); } } /** * 读取文件内容 * * @param input * 输入流 * @param line * 是否换行(true:换行,false:非换行) * @return 文件内容 * @throws IOException */ public static final String readString(InputStream input, boolean line) { InputStreamReader reader = null ; try { reader = new InputStreamReader(input); return readString(reader, line); } catch (Exception e) { throw new ServiceException(e); } finally { IOUtils.closeQuietly(reader); } } /** * 读取文件内容 * * @param input * 输入流 * @param line * 是否换行(true:换行,false:非换行) * @return 文件内容 * @throws IOException */ public static final String readString(Reader input, boolean line) { BufferedReader reader = null ; try { StringBuffer sb = new StringBuffer(); reader = new BufferedReader(input); String lineString = reader.readLine(); lineString = IOUtils.readFirstLine(lineString); if (line) { while (lineString != null ) { if (CheckUtil.isNotNull(sb.toString())) { sb.append(IOUtils.LINE_SEPARATOR); } sb.append(lineString); lineString = reader.readLine(); } } else { while (lineString != null ) { sb.append(lineString); lineString = reader.readLine(); } } return sb.toString(); } catch (Exception e) { throw new ServiceException(e); } finally { IOUtils.closeQuietly(reader); } } /** * * @param file * 文件对象 * @param maxLine * 最大行 * @return */ public static final String readLine(File file, long maxLine) { return readLine(file, "UTF-8" , true , maxLine); } /** * * @param file * 文件对象 * @param encoding * 编码 * @param maxLine * 最大行 * @return */ public static final String readLine(File file, String encoding, long maxLine) { return readLine(file, encoding, true , maxLine); } /** * 读取文件内容 * * @param file * 文件对象 * @param encoding * 编码 * @param line * 是否换行(true:换行,false:非换行) * @return 文件内容 * @throws IOException */ public static final String readLine(File file, String encoding, boolean line, long maxLine) { InputStream in = null ; InputStreamReader isr = null ; BufferedReader br = null ; try { StringBuffer sb = new StringBuffer(); in = FileUtils.openInputStream(file); isr = new InputStreamReader(in, encoding); br = new BufferedReader(isr); // 临时行数 long tmpLine = 0 ; String lineString = br.readLine(); tmpLine++; lineString = IOUtils.readFirstLine(lineString); if (line) { while (lineString != null ) { if (maxLine > 0 && tmpLine > maxLine) { break ; } if (CheckUtil.isNotNull(sb.toString())) { sb.append(IOUtils.LINE_SEPARATOR); } sb.append(lineString); lineString = br.readLine(); tmpLine++; } } else { while (lineString != null ) { if (maxLine > 0 && tmpLine > maxLine) { break ; } sb.append(lineString); lineString = br.readLine(); tmpLine++; } } return sb.toString(); } catch (Exception e) { throw new ServiceException(e); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(isr); IOUtils.closeQuietly(br); } } // readLines // ----------------------------------------------------------------------- public static final <T extends Collection<String>> void readLines(T t, File file) { readLines(t, file, null ); } public static final <T extends Collection<String>> void readLines(T t, File file, String encoding) { InputStream in = null ; try { in = FileUtils.openInputStream(file); readLines(t, in, encoding); } catch (Exception e) { throw new ServiceException(e); } finally { IOUtils.closeQuietly(in); } } public static final <T extends Collection<String>> void readLines(T t, InputStream input, String encoding) { try { if (encoding == null ) { readLines(t, input); } else { InputStreamReader reader = new InputStreamReader(input, encoding); readLines(t, reader); } } catch (Exception e) { throw new ServiceException(e); } } public static final <T extends Collection<String>> void readLines(T t, InputStream input) { InputStreamReader reader = new InputStreamReader(input); readLines(t, reader); } public static final <T extends Collection<String>> void readLines(T t, Reader input) { try { Collection<String> coll = getColl(t); BufferedReader reader = new BufferedReader(input); String line = reader.readLine(); line = IOUtils.readFirstLine(line); while (line != null ) { coll.add(line); line = reader.readLine(); } } catch (Exception e) { throw new ServiceException(e); } } // readLinesCountI // ----------------------------------------------------------------------- public static final <T extends Collection<String>> KV<Long, Long> readLinesCountI(File file, ReadLinesCallI<T> call) { return readLinesCountI(file, null , call); } public static final <T extends Collection<String>> KV<Long, Long> readLinesCountI(File file, String encoding, ReadLinesCallI<T> call) { InputStream in = null ; try { in = FileUtils.openInputStream(file); return readLinesCountI(in, encoding, call); } catch (Exception e) { throw new ServiceException(e); } finally { IOUtils.closeQuietly(in); } } public static final <T extends Collection<String>> KV<Long, Long> readLinesCountI(InputStream input, String encoding, ReadLinesCallI<T> call) { try { if (encoding == null ) { return readLinesCountI(input, call); } else { InputStreamReader reader = new InputStreamReader(input, encoding); return readLinesCountI(reader, call); } } catch (Exception e) { throw new ServiceException(e); } } public static final <T extends Collection<String>> KV<Long, Long> readLinesCountI(InputStream input, ReadLinesCallI<T> call) { InputStreamReader reader = new InputStreamReader(input); return readLinesCountI(reader, call); } /** * 读取大文件 * * @param input * 输入流 * @param call * 回调 * @return {@code KV<总行数,实际行数>} * @throws IOException */ public static final <T extends Collection<String>> KV<Long, Long> readLinesCountI(Reader input, ReadLinesCallI<T> call) { long totalLineNum = 0 ; long lineNum = 0 ; try { BufferedReader reader = new BufferedReader(input); String line = reader.readLine(); line = IOUtils.readFirstLine(line); long startLineNum = call.getStartLineNum(); long endLineNum = call.getEndLineNum(); String linePrev = null ; String lineNext = null ; boolean first = true ; while (line != null ) { totalLineNum++; if (first) { // 这里只读取一次 // 读取下下一行 lineNext = reader.readLine(); first = false ; } // 是否中断 if (call.interrupt(linePrev, line, lineNext, totalLineNum)) { break ; } if (startLineNum <= totalLineNum && (endLineNum <= 0 || endLineNum >= totalLineNum)) { // 开始/结束行区间数据 KV<String, Boolean> kv = call.changeLine(linePrev, line, lineNext, totalLineNum); if (kv != null ) { line = kv.getK(); boolean filter = kv.getV(); // 是否过虑 if (filter) { lineNum++; } } } // 赋值上一行 linePrev = line; // 读取下一行 line = lineNext; if (line != null ) { // 读取下下一行 lineNext = reader.readLine(); } } } catch (Exception e) { throw new ServiceException(e); } return KV.with(totalLineNum, lineNum); } // readLinesI // ----------------------------------------------------------------------- public static final <T extends Collection<String>> T readLinesI(File file, ReadLinesCallI<T> call) { return readLinesI(file, null , call); } public static final <T extends Collection<String>> T readLinesI(File file, String encoding, ReadLinesCallI<T> call) { InputStream in = null ; try { in = FileUtils.openInputStream(file); return readLinesI(in, encoding, call); } catch (Exception e) { throw new ServiceException(e); } finally { IOUtils.closeQuietly(in); } } public static final <T extends Collection<String>> T readLinesI(InputStream input, String encoding, ReadLinesCallI<T> call) { try { if (encoding == null ) { return readLinesI(input, call); } else { InputStreamReader reader = new InputStreamReader(input, encoding); return readLinesI(reader, call); } } catch (Exception e) { throw new ServiceException(e); } } public static final <T extends Collection<String>> T readLinesI(InputStream input, ReadLinesCallI<T> call) { InputStreamReader reader = new InputStreamReader(input); return readLinesI(reader, call); } /** * 把文件中每一行设置到集合中(never return null) * * @param input * @param call * @return * @throws IOException */ @SuppressWarnings ( "unchecked" ) public static final <T extends Collection<String>> T readLinesI(Reader input, ReadLinesCallI<T> call) { try { T t = call.getObj(); Collection<String> coll = getColl(t); BufferedReader reader = new BufferedReader(input); String line = reader.readLine(); line = IOUtils.readFirstLine(line); long startLineNum = call.getStartLineNum(); long endLineNum = call.getEndLineNum(); long totalLineNum = 0 ; String linePrev = null ; String lineNext = null ; boolean first = true ; while (line != null ) { totalLineNum++; if (first) { // 这里只读取一次 // 读取下下一行 lineNext = reader.readLine(); first = false ; } // 是否中断 if (call.interrupt(linePrev, line, lineNext, totalLineNum)) { break ; } if (startLineNum <= totalLineNum && (endLineNum <= 0 || endLineNum >= totalLineNum)) { // 开始/结束行区间数据 KV<String, Boolean> kv = call.changeLine(linePrev, line, lineNext, totalLineNum); if (kv != null ) { line = kv.getK(); boolean filter = kv.getV(); // 是否过虑 if (filter) { coll.add(line); } } } // 赋值上一行 linePrev = line; // 读取下一行 line = lineNext; if (line != null ) { // 读取下下一行 lineNext = reader.readLine(); } } return (T) coll; } catch (Exception e) { throw new ServiceException(e); } } // readLinesBatchI // ----------------------------------------------------------------------- public static final <T extends Collection<String>> List<T> readLinesBatchI(File file, ReadLinesCallI<T> call, ReadLinesBatchCallI<T> batchI) { return readLinesBatchI(file, null , call, batchI); } /** * 把文件中每一行设置到批量集合中(never return null) * * @param file * @param encoding * @param call * @param batchI * @return * @throws IOException */ public static final <T extends Collection<String>> List<T> readLinesBatchI(File file, String encoding, ReadLinesCallI<T> call, ReadLinesBatchCallI<T> batchI) { List<T> lists = new ArrayList<T>(); // 获取总数 KV<Long, Long> kv = readLinesCountI(file, call); long size = kv.getV(); if (size > 0 ) { long start = System.currentTimeMillis(); long batchSize = batchI.getBatchSize(); if (batchSize > 1 ) { long preNum = size / batchSize; long modNum = size % batchSize; // 100/10=10 for ( long i = 1 ; i <= preNum; i++) { call.setStartLineNum((i - 1 ) * batchSize + 1 ); call.setEndLineNum(i * batchSize); setBatchCollI(file, encoding, call, batchI, lists); } if (modNum == 0 ) { } else { // 11/3=3...2 // 设置剩余的量 call.setStartLineNum(preNum * batchSize + 1 ); call.setEndLineNum(size); setBatchCollI(file, encoding, call, batchI, lists); } } else { setBatchCollI(file, encoding, call, batchI, lists); } long end = System.currentTimeMillis(); long x = (end - start) / 1000 ; long y = (end - start) % 1000 ; logger.debug( "全部读取完毕...,总执行时间:" + (end - start) + "毫秒," + x + "." + (y < 100 ? "0" + y : y) + "秒" ); } return lists; } /** * 批量设置集合 * * @param file * @param encoding * @param call * @param batchI * @param lists * @throws IOException */ private static <T extends Collection<String>> void setBatchCollI(File file, String encoding, ReadLinesCallI<T> call, ReadLinesBatchCallI<T> batchI, List<T> lists) { logger.debug( "正在读取..." + (call.getEndLineNum() <= 0 ? "全部数据" : "[" + call.getStartLineNum() + "-" + call.getEndLineNum() + "]行数据" )); long start = System.currentTimeMillis(); T t = readLinesI(file, encoding, call); if (batchI.isCallBatchColl()) { batchI.callBatchColl(t); } else { lists.add(t); } long end = System.currentTimeMillis(); long x = (end - start) / 1000 ; long y = (end - start) % 1000 ; logger.debug( "读取完毕..." + (call.getEndLineNum() <= 0 ? "全部数据" : "[" + call.getStartLineNum() + "-" + call.getEndLineNum() + "]行数据" ) + ",执行时间:" + (end - start) + "毫秒," + x + "." + (y < 100 ? "0" + y : y) + "秒" ); } /** * 获取对应的集合类型 * * @param t * @return * @throws IOException */ private static <T extends Collection<String>> Collection<String> getColl(T t) { Collection<String> coll = null ; if (t instanceof List) { coll = (List<String>) t; } else if (t instanceof Set) { coll = (Set<String>) t; } else { throw new ServiceException( "不支持的返回类型" + t); } return coll; } /** * 查找冲突jar包 * * @param path * 所要查找的JAR包的目录 * @param className * 要查询的class,要带包名的类名 * @return */ public static final List<String> findClassConflictJar(String path, String className) { List<String> results = new ArrayList<String>(); className = className.replace( '.' , '/' ) + ".class" ; findClassConflictJar(path, className, results); return results; } /** * 查找冲突jar包 * * @param path * 所要查找的JAR包的目录 * @param className * 要查询的class,要带包名的类名 * @param results * 冲突的jar文件路径集合 */ private static final void findClassConflictJar(String path, String className, List<String> results) { path = changePathSeparator(path, ConstantForEnum.ChangePathLastSeparator.ADD_AFTER); File file = new File(path); if (!file.exists()) { logger.warn( "文件[" + file.getAbsolutePath() + "]不存在" ); return ; } if (file.isFile()) { logger.warn( "文件[" + file.getAbsolutePath() + "]不是目录,强制返回结果" ); return ; } String[] filelist = file.list(); if (filelist == null ) { logger.warn( "文件[" + file.getAbsolutePath() + "]中没有任何文件,强制返回结果" ); return ; } for ( int i = 0 ; i < filelist.length; i++) { String filePath = filelist[i]; File temp = new File(path + filePath); // if ((temp.isDirectory() && !temp.isHidden() && temp.exists())) { if (temp.isDirectory()) { findClassConflictJar(path + filePath, className, results); } else { if (filePath.toLowerCase().endsWith( "jar" )) { try { java.util.jar.JarFile jarfile = new java.util.jar.JarFile(path + filePath); for (Enumeration<JarEntry> e = jarfile.entries(); e.hasMoreElements();) { String name = e.nextElement().toString(); if (name.equals(className) || name.indexOf(className) > - 1 ) { // System.out.println(path + filePath); results.add(path + filePath); } jarfile.close(); } } catch (Exception e) { e.printStackTrace(); } } } } } // /** // * 查找冲突jar包 // * // * @param objPath // * jar文件或目录对象 // * @param jarClass // * 每个jar路径对应的class集合 // * @param classResult // * 所有class(包路径)对应的jar文件路径 // * @param conflictClass // * 冲突class(包路径)对应的jar文件路径 // */ // @SuppressWarnings("unchecked") // public static final void findJarConflictClass(Object objPath, Map<String, Set<JarClass>> jarClassResult, Map<String, Set<String>> classResult, Map<String, Set<String>> conflictResult) { @SuppressWarnings ( "unchecked" ) public static final void findJarConflictClass(JarParams params) { Collection<String> values = null ; Object objPath = params.getObjPath(); if (CheckUtil.isNull(objPath)) { // 如果没有设置objPath,则默认path为objPath值 objPath = params.getPath(); } if (objPath instanceof String) { // 此处不会被执行 values = new HashSet<String>(); values.add(String.valueOf(objPath)); } else if (objPath instanceof Collection) { values = ((Collection<String>) objPath); } else if (objPath instanceof String[]) { values = Arrays.asList((String[]) objPath); } if (values == null || values.size() == 0 ) { logger.warn( "jar文件或目录对象数据格式不正确" ); return ; } // 循环写 Iterator<String> it = values.iterator(); while (it.hasNext()) { // doFindJarConflictClass(it.next(), jarClassResult, classResult, conflictResult); // 设置path值 params.setPath(it.next()); doFindJarConflictClass(params); } } // /** // * 查找冲突jar包 // * // * @param path // * jar文件或目录路径 // * @param jarClass // * 每个jar路径对应的class集合 // * @param classResult // * 所有class(包路径)对应的jar文件路径 // * @param conflictClass // * 冲突class(包路径)对应的jar文件路径 // */ // public static final void findJarConflictClass(String path, Map<String, Set<JarClass>> jarClassResult, Map<String, Set<String>> classResult, Map<String, Set<String>> conflictResult) { private static final void doFindJarConflictClass( final JarParams params) { final String path = changePathSeparator(params.getPath(), ConstantForEnum.ChangePathLastSeparator.ADD_AFTER); final Map<String, Set<JarClass>> jarClassResult = params.getJarClassResult(); final Map<String, Set<String>> classResult = params.getClassResult(); final Map<String, Set<String>> conflictResult = params.getConflictResult(); File file = new File(path); if (!file.exists()) { logger.warn( "文件[" + file.getAbsolutePath() + "]不存在" ); return ; } if (file.isFile()) { logger.warn( "文件[" + file.getAbsolutePath() + "]不是目录,强制返回结果" ); return ; } final String[] filelist = file.list( new FilenameFilter() { @Override public boolean accept(File dir, String name) { // System.out.println(dir + "," + name + "," + FilenameUtils.getExtension(name)); String extension = FilenameUtils.getExtension(name); if (CheckUtil.isNotNull(extension)) { if ( "jar" .equals(extension.toLowerCase())) { return true ; } } return false ; } }); if (filelist == null || filelist.length == 0 ) { logger.warn( "文件[" + file.getAbsolutePath() + "]中没有任何文件,强制返回结果" ); return ; } for ( int i = 0 ; i < filelist.length; i++) { final String filePath = filelist[i]; doJarClass(params, path, jarClassResult, classResult, conflictResult, filePath); } } /** * 处理jar中的class * * @param params * @param path * @param jarClassResult * @param classResult * @param conflictResult * @param filePath */ private static final void doJarClass( final JarParams params, final String path, final Map<String, Set<JarClass>> jarClassResult, final Map<String, Set<String>> classResult, final Map<String, Set<String>> conflictResult, final String filePath) { File temp = new File(path + filePath); // if ((temp.isDirectory() && !temp.isHidden() && temp.exists())) { if (temp.isDirectory()) { // findJarConflictClass(path + filePath, jarClassResult, conflictResult, classResult); doFindJarConflictClass(params); } else { try { String jarPath = changePathSeparator(path + filePath); // System.out.println(jarPath); Set<JarClass> jarClasss = null ; // 可以为null if (jarClassResult != null ) { jarClasss = jarClassResult.get(jarPath); if (jarClasss == null ) { // 不存在 jarClasss = new HashSet<JarClass>(); jarClassResult.put(jarPath, jarClasss); } } java.util.jar.JarFile jarfile = new java.util.jar.JarFile(path + filePath); for (Enumeration<JarEntry> e = jarfile.entries(); e.hasMoreElements();) { // 获取jar文件 String classPath = e.nextElement().toString(); String extension = FilenameUtils.getExtension(classPath); String fullPath = jarPath + "!" + classPath; // 是否是class文件 if ( "class" .equals(extension.toLowerCase())) { // 转换为class包 int index = classPath.lastIndexOf( "." ); String prefixClassName = classPath; if (index > - 1 ) { prefixClassName = classPath.substring( 0 , index); } String className = prefixClassName.replaceAll( "/" , "." ); // 添加class Set<String> classJars = classResult.get(className); if (classJars == null ) { classJars = new HashSet<String>(); classResult.put(className, classJars); } else { // 冲突了 Set<String> classConflictJars = conflictResult.get(className); if (classConflictJars == null ) { classConflictJars = new HashSet<String>(); conflictResult.put(className, classConflictJars); } // 添加jar文件(会自动去重) classConflictJars.add(jarPath); // 添加冲突的class对应的所有jar文件路径 classConflictJars.addAll(classJars); } classJars.add(jarPath); if (jarClasss != null ) { JarClass jarClass = new JarClass(); // 设置jar属性 jarClass.setFileDir(path); jarClass.setClassPath(classPath); jarClass.setClassName(className); jarClass.setFullPath(fullPath); jarClasss.add(jarClass); } } else { logger.debug( "文件[" + fullPath + "]不是class文件,继续查找" ); } } jarfile.close(); } catch (Exception e) { e.printStackTrace(); } } } /** * 写文件 * * @param filePath * 文件路径 * @param content * 文件内容 * @throws IOException */ public static final void write(String filePath, String content) { write( new File(filePath), content, "UTF-8" ); } /** * 写文件 * * @param filePath * 文件路径 * @param content * 文件内容 * @param encoding * 编码 * @throws IOException */ public static final void write(String filePath, String content, String encoding) { write( new File(filePath), content, encoding); } /** * 写文件 * * @param filePath * 文件对象 * @param content * 文件内容 * @throws IOException */ public static final void write(File file, String content) { write(file, content, null ); } /** * 写文件 * * @param filePath * 文件对象 * @param content * 文件内容 * @param encoding * 编码 * @throws IOException */ public static final void write(File file, String content, String encoding) { try { createFolderOrFile(file, false ); if (file == null ) return ; if (CheckUtil.isNull(content)) { content = "" ; } if (CheckUtil.isNull(encoding)) { encoding = "UTF-8" ; } BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(file)); OutputStreamWriter writer = new OutputStreamWriter(bos, encoding); writer.write(content); writer.flush(); writer.close(); } catch (Exception e) { throw new ServiceException(e); } } /** * 写文件 * * @param content * 文件字节内容 * @param encoding * 编码 * @throws IOException */ public static void write( byte [] content, File outFile) { FileOutputStream fout = null ; try { createFolderOrFile(outFile); fout = new FileOutputStream(outFile); fout.write(content); fout.flush(); } catch (Exception e) { throw new ServiceException(e); } finally { if (fout != null ) { try { fout.close(); } catch (Exception e2) { } } } } /** * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 * * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @return 页面地址 */ public static final String GetImageStr(String imgFilePath) { byte [] data = null ; BufferedInputStream bis = null ; // 读取图片字节数组 try { bis = new BufferedInputStream( new FileInputStream(imgFilePath)); data = new byte [bis.available()]; bis.read(data); } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null ) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); // 返回Base64编码过的字节数组字符串 return encoder.encode(data); } /** * 对字节数组字符串进行Base64解码并生成图片 * * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @return 页面地址 */ public static final boolean GenerateImage(String imgStr, String imgFilePath) { // 图像数据为空 if (imgStr == null ) return false ; if (imgStr.indexOf( "data:image/jpeg;base64," ) != - 1 ) { imgStr = imgStr.substring( "data:image/jpeg;base64," .length()); } BASE64Decoder decoder = new BASE64Decoder(); BufferedOutputStream bos = null ; try { // Base64解码 byte [] bytes = decoder.decodeBuffer(imgStr); for ( int i = 0 ; i < bytes.length; ++i) { if (bytes[i] < 0 ) { // 调整异常数据 bytes[i] += 256 ; } } // 生成jpeg图片 bos = new BufferedOutputStream( new FileOutputStream(imgFilePath)); bos.write(bytes); bos.flush(); return true ; } catch (Exception e) { e.printStackTrace(); return false ; } finally { if (bos != null ) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } } } } |
本文为张军原创文章,转载无需和我联系,但请注明来自张军的军军小站,个人博客http://www.zhangjunbk.com