分享一个文件的工具类

   1 package com.cn.shupu.util;
   2 
   3 import java.io.BufferedReader;
   4 import java.io.File;
   5 import java.io.FileInputStream;
   6 import java.io.FileNotFoundException;
   7 import java.io.FileOutputStream;
   8 import java.io.FileWriter;
   9 import java.io.IOException;
  10 import java.io.InputStream;
  11 import java.io.InputStreamReader;
  12 import java.io.OutputStream;
  13 import java.io.RandomAccessFile;
  14 import java.nio.ByteBuffer;
  15 import java.nio.channels.FileChannel;
  16 import java.text.DecimalFormat;
  17 import java.text.ParseException;
  18 import java.text.SimpleDateFormat;
  19 import java.util.ArrayList;
  20 import java.util.Arrays;
  21 import java.util.Collections;
  22 import java.util.Date;
  23 import java.util.HashMap;
  24 import java.util.List;
  25 import java.util.Map;
  26 import java.util.Random;
  27 
  28 import org.springframework.web.multipart.MultipartFile;
  29 import org.springframework.web.multipart.MultipartHttpServletRequest;
  30 import org.springframework.web.multipart.commons.CommonsMultipartFile;
  31 
  32 import net.sf.json.JSONObject;
  33 
  34 /**
  35  * 文件工具类 涵盖绝大多数的文件操作
  36  *  38  * @version 创建时间:2016年11月14日 下午3:03:21
  39  */
  40 public class FileTools {
  41     public FileTools() {
  42 
  43     }
  44 
  45     /**
  46      * formatPath 转义文件目录
  47      *
  48      * @param path
  49      * @return
  50      */
  51     public static String formatPath(String path) {
  52         return path.replaceAll("\\", "/");
  53     }
  54 
  55     /**
  56      * combainPath文件路径合并
  57      *
  58      * @param eins
  59      * @param zwei
  60      * @return
  61      */
  62     private static String combainPath(String eins, String zwei) {
  63         String dori = "";
  64         eins = null == eins ? "" : formatPath(eins);
  65         zwei = null == zwei ? "" : formatPath(zwei);
  66         if (!eins.endsWith("/") && zwei.indexOf("/") != 0) {
  67             dori = eins + "/" + zwei;
  68         } else {
  69             dori = (eins + zwei).replaceAll("//", "/");
  70         }
  71         return dori;
  72     }
  73 
  74     /**
  75      * list2Array 列表转换数组
  76      *
  77      * @param list
  78      * @return
  79      */
  80     private static String[] list2Array(List list) {
  81         String array[] = (String[]) list.toArray(new String[list.size()]);
  82         return array;
  83     }
  84 
  85     /**
  86      * cp 复制文件
  87      *
  88      * @param source
  89      * @param destination
  90      * @param loop
  91      * @return
  92      */
  93     public static List<File> cp(String source, String destination, boolean loop) {
  94         List<File> list = new ArrayList();
  95         try {
  96             File srcFile = new File(source);
  97             File desFile = new File(destination);
  98             list.addAll(cp(srcFile, desFile, loop));
  99         } catch (Exception ex) {
 100             ex.printStackTrace();
 101         }
 102         return list;
 103     }
 104 
 105     /**
 106      * cp 复制文件
 107      *
 108      * @param source
 109      * @param destination
 110      * @param loop
 111      * @return
 112      */
 113     public static List<File> cp(File source, File destination, boolean loop) {
 114         List<File> list = new ArrayList();
 115         try {
 116             if (!source.exists() || source.isDirectory()) {
 117                 throw new FileNotFoundException();
 118             }
 119             list.add(cp(source, destination));
 120             if (loop) {
 121                 String[] subFile = source.list();
 122                 for (String subPath : subFile) {
 123                     String src = combainPath(source.getPath(), subPath);// 子文件原文件路径
 124                     String des = combainPath(destination.getPath(), subPath);// 子文件目标路径
 125                     File subfile = new File(src);
 126                     if (subfile.isFile()) {
 127                         list.add(cp(src, des));
 128                     } else if (subfile.isDirectory() && loop) {
 129                         list.addAll(cp(src, des, loop));
 130                     }
 131                 }
 132             }
 133         } catch (Exception ex) {
 134             ex.printStackTrace();
 135         }
 136         return list;
 137     }
 138 
 139     /**
 140      * cp 单文件复制文件
 141      *
 142      * @param source
 143      * @param destination
 144      * @return
 145      */
 146     public static File cp(String source, String destination) {
 147         File desFile = null;
 148         try {
 149             File srcFile = new File(source);
 150             desFile = new File(destination);
 151             desFile = cp(srcFile, desFile);
 152         } catch (Exception ex) {
 153             ex.printStackTrace();
 154         }
 155         return desFile;
 156     }
 157 
 158     /**
 159      * cp 单文件复制文件
 160      *
 161      * @param source
 162      * @param destination
 163      * @return
 164      */
 165     public static File cp(File source, File destination) {
 166         FileInputStream in = null;
 167         FileOutputStream out = null;
 168         FileChannel inc = null;
 169         FileChannel outc = null;
 170         try {
 171             if (!source.exists() || source.isDirectory()) {
 172                 throw new FileNotFoundException();
 173             }
 174             if (source.getPath().equals(destination.getPath())) {
 175                 return source;
 176             }
 177             long allbytes = du(source, false);
 178             if (!destination.exists()) {
 179                 destination.createNewFile();
 180             }
 181             in = new FileInputStream(source.getPath());
 182             out = new FileOutputStream(destination);
 183             inc = in.getChannel();
 184             outc = out.getChannel();
 185             ByteBuffer byteBuffer = null;
 186             long length = 2097152;// 基本大小,默认2M
 187             long _2M = 2097152;
 188             while (inc.position() < inc.size()) {
 189                 if (allbytes > (64 * length)) {// 如果文件大小大于128M 缓存改为64M
 190                     length = 32 * _2M;
 191                 } else if (allbytes > (32 * length)) {// 如果文件大小大于64M 缓存改为32M
 192                     length = 16 * _2M;
 193                 } else if (allbytes > (16 * length)) {// 如果文件大小大于32M 缓存改为16M
 194                     length = 8 * _2M;
 195                 } else if (allbytes > (8 * length)) {// 如果文件大小大于16M 缓存改为8M
 196                     length = 4 * _2M;
 197                 } else if (allbytes > (4 * length)) {// 如果文件大小大于8M 缓存改为4M
 198                     length = 2 * _2M;
 199                 } else if (allbytes > (2 * length)) {// 如果文件大小大于4M 缓存改为2M
 200                     length = _2M;
 201                 } else if (allbytes > (length)) {// 如果文件大小大于2M 缓存改为1M
 202                     length = _2M / 2;
 203                 } else if (allbytes < length) {// 如果文件小于基本大小,直接输出
 204                     length = allbytes;
 205                 }
 206                 allbytes = inc.size() - inc.position();
 207                 byteBuffer = ByteBuffer.allocateDirect((int) length);
 208                 inc.read(byteBuffer);
 209                 byteBuffer.flip();
 210                 outc.write(byteBuffer);
 211                 outc.force(false);
 212             }
 213         } catch (Exception ex) {
 214             ex.printStackTrace();
 215         } finally {
 216             try {
 217                 if (null != inc) {
 218                     inc.close();
 219                 }
 220                 if (null != outc) {
 221                     outc.close();
 222                 }
 223                 if (null != in) {
 224                     in.close();
 225                 }
 226                 if (null != out) {
 227                     out.close();
 228                 }
 229             } catch (Exception ex) {
 230                 ex.printStackTrace();
 231             }
 232         }
 233         return destination;
 234     }
 235 
 236     /**
 237      * rename 文件重命名
 238      *
 239      * @param filePath
 240      * @param from
 241      * @param to
 242      * @return
 243      */
 244     public static File rename(String filePath, String from, String to) {
 245         File newFile = null;
 246         try {
 247             File oldFile = new File(combainPath(filePath, from));
 248             newFile = new File(combainPath(filePath, to));
 249             rename(newFile, oldFile);
 250         } catch (Exception ex) {
 251             ex.printStackTrace();
 252         }
 253         return newFile;
 254     }
 255 
 256     /**
 257      * rename 文件重命名
 258      *
 259      * @param to
 260      * @param from
 261      * @return
 262      */
 263     public static File rename(File from, File to) {
 264         try {
 265             String newPath = to.getPath();
 266             String oldPath = from.getPath();
 267             if (!oldPath.equals(newPath)) {
 268                 if (!to.exists()) {
 269                     from.renameTo(to);
 270                 }
 271             }
 272         } catch (Exception ex) {
 273             ex.printStackTrace();
 274         }
 275         return to;
 276     }
 277 
 278     /**
 279      * mv 移动文件
 280      *
 281      * @param fileName
 282      * @param source
 283      * @param destination
 284      * @param cover
 285      */
 286     public static void mv(String fileName, String source, String destination, boolean cover) {
 287         try {
 288             if (!source.equals(destination)) {
 289                 File oldFile = new File(combainPath(source, fileName));
 290                 File newFile = new File(combainPath(destination, fileName));
 291                 mv(oldFile, newFile, cover);
 292             }
 293         } catch (Exception ex) {
 294             ex.printStackTrace();
 295         }
 296     }
 297 
 298     /**
 299      * mv 移动文件
 300      *
 301      * @param source
 302      * @param destination
 303      * @param cover
 304      */
 305     public static void mv(String source, String destination, boolean cover) {
 306         try {
 307 
 308             if (!new File(destination).exists())
 309                 new File(destination).mkdirs();
 310 
 311             if (!source.equals(destination)) {
 312                 File oldFile = new File(source);
 313                 File newFile = new File(destination);
 314                 mv(oldFile, newFile, cover);
 315             }
 316         } catch (Exception ex) {
 317             ex.printStackTrace();
 318         }
 319     }
 320 
 321     /**
 322      * mv 移动文件
 323      *
 324      * @param source
 325      * @param destination
 326      * @param cover
 327      */
 328     public static void mv(File source, File destination, boolean cover) {
 329         try {
 330             if (!source.exists()) {
 331                 throw new FileNotFoundException();
 332             }
 333             StringBuilder fileName = new StringBuilder(source.getName());
 334             if (!cover && source.getPath().equals(destination.getPath())) {
 335 
 336                 if (fileName.indexOf(".") > 0) {
 337 
 338                     fileName.insert(fileName.lastIndexOf("."), "_副本");
 339 
 340                 } else {
 341                     fileName.append("_副本");
 342                 }
 343                 cp(source, new File(combainPath(source.getParent(), fileName.toString())));
 344             } else {
 345                 source.renameTo(destination);
 346             }
 347         } catch (Exception ex) {
 348             ex.printStackTrace();
 349         }
 350     }
 351 
 352     /**
 353      * extensions 获取文件扩展名信息
 354      *
 355      * @param filePath
 356      * @param fileName
 357      * @return
 358      */
 359     private static String[] extensions(String filePath, String fileName) {
 360         String[] extension = {};
 361         try {
 362             String fullPath = combainPath(filePath, fileName);
 363             File file = new File(fullPath);
 364             extensions(file);
 365         } catch (Exception ex) {
 366             ex.printStackTrace();
 367         }
 368         return extension;
 369     }
 370 
 371     /**
 372      * extensions 获取文件扩展名信息
 373      *
 374      * @param fullPath
 375      * @return
 376      */
 377     private static String[] extensions(String fullPath) {
 378         String[] extension = {};
 379         try {
 380             File file = new File(fullPath);
 381             extensions(file);
 382         } catch (Exception ex) {
 383             ex.printStackTrace();
 384         }
 385         return extension;
 386     }
 387 
 388     /**
 389      * extensions 获取文件扩展名信息
 390      *
 391      * @param file
 392      * @return
 393      */
 394     private static String[] extensions(File file) {
 395         String[] extension = {};
 396         try {
 397             if (file.isFile()) {
 398                 String fileName = file.getName();
 399                 if (fileName.lastIndexOf(".") >= 0) {
 400                     int lastIndex = fileName.lastIndexOf(".");
 401                     extension[0] = String.valueOf(lastIndex);// 扩展名的“.”的索引
 402                     extension[1] = fileName.substring(lastIndex + 1);// 扩展名
 403                     extension[2] = fileName.substring(0, lastIndex);// 文件名
 404                 }
 405             }
 406         } catch (Exception ex) {
 407             ex.printStackTrace();
 408         }
 409         return extension;
 410     }
 411 
 412     /**
 413      * ls 遍历文件
 414      *
 415      * @param filePath
 416      * @param loop
 417      * @return
 418      */
 419     public static List<File> ls(String filePath, boolean loop) {
 420         List<File> list = new ArrayList();
 421         try {
 422             File file = new File(filePath);
 423             list.addAll(ls(file, loop));
 424         } catch (Exception ex) {
 425             ex.printStackTrace();
 426         }
 427         return list;
 428     }
 429 
 430     /**
 431      * ls 遍历文件
 432      *
 433      * @param file
 434      * @param loop
 435      * @return
 436      */
 437     public static List<File> ls(File file, boolean loop) {
 438         List<File> list = new ArrayList();
 439         try {
 440             list.add(file);
 441             if (!file.isDirectory()) {
 442                 list.add(file);
 443             } else if (file.isDirectory()) {
 444                 File[] subList = file.listFiles();
 445                 subList = filesSort(subList, true);
 446                 for (File subFile : subList) {
 447                     if (subFile.isDirectory() && loop) {
 448                         list.addAll(ls(subFile.getPath(), loop));
 449                     } else {
 450                         list.add(subFile);
 451                     }
 452                 }
 453             }
 454         } catch (Exception ex) {
 455             ex.printStackTrace();
 456         }
 457         return list;
 458     }
 459 
 460     /**
 461      * ls 遍历文件
 462      *
 463      * @param filePath
 464      * @param loop
 465      * @return
 466      */
 467     public static List<File> getFiles(String filePath, boolean loop) {
 468         List<File> list = new ArrayList();
 469 
 470         try {
 471             File file = new File(filePath);
 472 
 473             list.addAll(getFiles(file, loop));
 474 
 475         } catch (Exception ex) {
 476             ex.printStackTrace();
 477         }
 478         return list;
 479     }
 480 
 481     /**
 482      * ls 遍历文件
 483      *
 484      * @param file
 485      * @param loop
 486      * @return
 487      */
 488     public static List<File> getFiles(File file, boolean loop) {
 489         List<File> list = new ArrayList();
 490         try {
 491             // list.add(file);
 492             if (!file.isDirectory()) {
 493                 list.add(file);
 494             } else if (file.isDirectory()) {
 495 
 496                 File[] subList = file.listFiles();
 497                 subList = filesSort(subList, true);
 498 
 499                 for (File subFile : subList) {
 500 
 501                     if (subFile.isDirectory() && loop) {
 502 
 503                         list.addAll(getFiles(subFile.getPath(), loop));
 504 
 505                     } else {
 506 
 507                         list.add(subFile);
 508 
 509                     }
 510 
 511                 }
 512 
 513             }
 514         } catch (Exception ex) {
 515             ex.printStackTrace();
 516         }
 517         return list;
 518     }
 519 
 520     /**
 521      * filesSort 文件排序(默认升序)
 522      *
 523      * @param parentPath
 524      * @param subList
 525      * @return
 526      */
 527     private static File[] filesSort(File[] inFiles, boolean asc) {
 528 
 529         List<String> files = new ArrayList();
 530 
 531         List<String> dirs = new ArrayList();
 532 
 533         for (File subFile : inFiles) {
 534             if (subFile.isDirectory()) {
 535                 dirs.add(subFile.getPath());
 536             } else if (subFile.isFile()) {
 537                 files.add(subFile.getPath());
 538             }
 539         }
 540 
 541         String[] fileArray = {};
 542 
 543         if (files.size() > 0) {
 544 
 545             fileArray = list2Array(files);
 546 
 547             Arrays.sort(fileArray);
 548 
 549             if (!asc) {
 550                 Arrays.sort(fileArray, Collections.reverseOrder());
 551             }
 552 
 553         }
 554         String[] dirArray = {};
 555         if (dirs.size() > 0) {
 556             dirArray = list2Array(dirs);
 557             Arrays.sort(dirArray);
 558             if (!asc) {
 559                 Arrays.sort(dirArray, Collections.reverseOrder());
 560             }
 561         }
 562         return concat2FileArray(fileArray, dirArray);
 563     }
 564 
 565     /**
 566      * concat2FileArray 合并文件数组
 567      *
 568      * @param old1
 569      * @param old2
 570      * @return
 571      */
 572     private static File[] concat2FileArray(String[] old1, String[] old2) {
 573         File[] newArray = new File[old1.length + old2.length];
 574         for (int i = 0, n = old1.length; i < n; i++) {
 575             newArray[i] = new File(old1[i]);
 576         }
 577         for (int i = 0, j = old1.length, n = (old1.length + old2.length); j < n; i++, j++) {
 578             newArray[j] = new File(old2[i]);
 579         }
 580         return newArray;
 581     }
 582 
 583     /**
 584      * read 读取文本文件
 585      *
 586      * @param filePath
 587      * @param fileName
 588      * @param charset
 589      * @return
 590      */
 591     public static StringBuilder read(String filePath, String fileName, String charset) {
 592         StringBuilder sb = new StringBuilder();
 593         try {
 594             String fullPath = combainPath(filePath, fileName);
 595             File file = new File(fullPath);
 596             sb.append(FileTools.tail(file, false, 0, charset));
 597         } catch (Exception ex) {
 598             ex.printStackTrace();
 599         }
 600         return sb;
 601     }
 602 
 603     /**
 604      * read 读取文本文件
 605      *
 606      * @param fullPath
 607      * @param charset
 608      * @return
 609      */
 610     public static StringBuilder read(String fullPath, String charset) {
 611         StringBuilder sb = new StringBuilder();
 612         try {
 613             File file = new File(fullPath);
 614             sb.append(FileTools.tail(file, false, 0, charset));
 615         } catch (Exception ex) {
 616             ex.printStackTrace();
 617         }
 618         return sb;
 619     }
 620 
 621     /**
 622      * read 读取文本文件
 623      *
 624      * @param file
 625      * @param charset
 626      * @return
 627      */
 628     public static StringBuilder read(File file, String charset) {
 629         StringBuilder sb = new StringBuilder();
 630         try {
 631             sb.append(FileTools.tail(file, false, 0, charset));
 632         } catch (Exception ex) {
 633             ex.printStackTrace();
 634         }
 635         return sb;
 636     }
 637 
 638     /**
 639      * find 读取文本文件指定行
 640      *
 641      * @param filePath
 642      * @param fileName
 643      * @param line
 644      * @param charset
 645      * @return
 646      */
 647     public static StringBuilder find(String filePath, String fileName, int line, String charset) {
 648         StringBuilder sb = new StringBuilder();
 649         try {
 650             String fullPath = combainPath(filePath, fileName);
 651             File file = new File(fullPath);
 652             sb.append(FileTools.tail(file, true, line, charset));
 653         } catch (Exception ex) {
 654             ex.printStackTrace();
 655         }
 656         return sb;
 657     }
 658 
 659     /**
 660      * find 读取文本文件指定行
 661      *
 662      * @param fullPath
 663      * @param line
 664      * @param charset
 665      * @return
 666      */
 667     public static StringBuilder find(String fullPath, int line, String charset) {
 668         StringBuilder sb = new StringBuilder();
 669         try {
 670             File file = new File(fullPath);
 671             sb.append(FileTools.tail(file, true, line, charset));
 672         } catch (Exception ex) {
 673             ex.printStackTrace();
 674         }
 675         return sb;
 676     }
 677 
 678     /**
 679      * find 读取文本文件指定行
 680      *
 681      * @param file
 682      * @param line
 683      * @param charset
 684      * @return
 685      */
 686     public static StringBuilder find(File file, int line, String charset) {
 687         StringBuilder sb = new StringBuilder();
 688         try {
 689             sb.append(FileTools.tail(file, true, line, charset));
 690         } catch (Exception ex) {
 691             ex.printStackTrace();
 692         }
 693         return sb;
 694     }
 695 
 696     /**
 697      * tail 读取文本文件
 698      *
 699      * @param filePath
 700      * @param fileName
 701      * @param charset
 702      * @param find
 703      * @param line
 704      * @return
 705      */
 706     public static StringBuilder tail(String filePath, String fileName, boolean find, int line, String charset) {
 707         StringBuilder sb = new StringBuilder();
 708         try {
 709             String fullPath = combainPath(filePath, fileName);
 710             File file = new File(fullPath);
 711             sb.append(FileTools.tail(file, find, line, charset));
 712         } catch (Exception ex) {
 713             ex.printStackTrace();
 714         }
 715         return sb;
 716     }
 717 
 718     /**
 719      * tail 读取文本文件
 720      *
 721      * @param fullPath
 722      * @param charset
 723      * @param find
 724      * @param line
 725      * @return
 726      */
 727     public static StringBuilder tail(String fullPath, boolean find, int line, String charset) {
 728         StringBuilder sb = new StringBuilder();
 729         try {
 730             File file = new File(fullPath);
 731             sb.append(FileTools.tail(file, find, line, charset));
 732         } catch (Exception ex) {
 733             ex.printStackTrace();
 734         }
 735         return sb;
 736     }
 737 
 738     /**
 739      * tail 读取文本文件
 740      *
 741      * @param file
 742      * @param charset
 743      * @param find
 744      * @param line
 745      * @return
 746      */
 747     public static StringBuilder tail(File file, boolean find, int line, String charset) {
 748         StringBuilder sb = new StringBuilder();
 749         BufferedReader bufferReader = null;
 750         if (null == charset || "".equals(charset)) {
 751             charset = "UTF-8";
 752         }
 753         try {
 754             if (!file.exists() || file.isDirectory()) {
 755                 throw new FileNotFoundException();
 756             }
 757             String fullPath = file.getPath();
 758             bufferReader = new BufferedReader(new InputStreamReader(new FileInputStream(fullPath), charset));
 759             String temp;
 760             for (int i = 0; (temp = bufferReader.readLine()) != null; i++) {
 761                 if (!find || line == i) {
 762                     sb.append(temp);
 763                 }
 764             }
 765         } catch (Exception ex) {
 766             ex.printStackTrace();
 767         } finally {
 768             if (null != bufferReader) {
 769                 try {
 770                     bufferReader.close();
 771                 } catch (IOException ex) {
 772                     ex.printStackTrace();
 773                 }
 774             }
 775         }
 776         return sb;
 777     }
 778 
 779     /**
 780      * sed 读取文本文件
 781      *
 782      * @param filePath
 783      * @param fileName
 784      * @param charset
 785      * @return
 786      */
 787     public static List<String> sed(String filePath, String fileName, String charset) {
 788         List<String> list = new ArrayList();
 789         try {
 790             String fullPath = combainPath(filePath, fileName);
 791             File file = new File(fullPath);
 792             list.addAll(FileTools.sed(file, charset));
 793         } catch (Exception ex) {
 794             ex.printStackTrace();
 795         }
 796         return list;
 797     }
 798 
 799     /**
 800      * sed 读取文本文件
 801      *
 802      * @param fullPath
 803      * @param charset
 804      * @return
 805      */
 806     public static List<String> sed(String fullPath, String charset) {
 807         List<String> list = new ArrayList();
 808         try {
 809             File file = new File(fullPath);
 810             list.addAll(FileTools.sed(file, charset));
 811         } catch (Exception ex) {
 812             ex.printStackTrace();
 813         }
 814         return list;
 815     }
 816 
 817     /**
 818      * sed 读取文本文件
 819      *
 820      * @param file
 821      * @param charset
 822      * @return
 823      */
 824     public static List<String> sed(File file, String charset) {
 825         List<String> list = new ArrayList();
 826         BufferedReader bufferReader = null;
 827         if (null == charset || "".equals(charset)) {
 828             charset = "UTF-8";
 829         }
 830         try {
 831             if (!file.exists() || file.isDirectory()) {
 832                 throw new FileNotFoundException();
 833             }
 834             String fullPath = file.getPath();
 835             bufferReader = new BufferedReader(new InputStreamReader(new FileInputStream(fullPath), charset));
 836             String temp;
 837             for (int i = 0; (temp = bufferReader.readLine()) != null; i++) {
 838                 list.add(temp);
 839             }
 840         } catch (Exception ex) {
 841             ex.printStackTrace();
 842         } finally {
 843             if (null != bufferReader) {
 844                 try {
 845                     bufferReader.close();
 846                 } catch (IOException ex) {
 847                     ex.printStackTrace();
 848                 }
 849             }
 850         }
 851         return list;
 852     }
 853 
 854     /**
 855      * cat 读取文本文件
 856      *
 857      * @param filePath
 858      * @param fileName
 859      * @return
 860      */
 861     public static byte[] cat(String filePath, String fileName) {
 862         byte[] output = {};
 863         try {
 864             String fullPath = combainPath(filePath, fileName);
 865             File file = new File(fullPath);
 866             output = FileTools.cat(file);
 867         } catch (Exception ex) {
 868             ex.printStackTrace();
 869         }
 870         return output;
 871     }
 872 
 873     /**
 874      * cat 读取文本文件
 875      *
 876      * @param fullPath
 877      * @return
 878      */
 879     public static byte[] cat(String fullPath) {
 880         byte[] output = {};
 881         try {
 882             File file = new File(fullPath);
 883             output = FileTools.cat(file);
 884         } catch (Exception ex) {
 885             ex.printStackTrace();
 886         }
 887         return output;
 888     }
 889 
 890     /**
 891      * cat 读取文本文件
 892      *
 893      * @param file
 894      * @return
 895      */
 896     public static byte[] cat(File file) {
 897         InputStream in = null;
 898         byte[] output = {};
 899         try {
 900             if (!file.exists() || file.isDirectory()) {
 901                 throw new FileNotFoundException();
 902             }
 903             String fullPath = file.getPath();
 904             long length = du(file, false);
 905             long _2M = 2097152;
 906             byte[] bytes = new byte[(int) length];
 907             in = new FileInputStream(fullPath);
 908             for (int count = 0; count != -1;) {
 909                 if (length > 16 * _2M) {
 910                     length = 4 * _2M;
 911                 } else if (length > 8 * _2M) {
 912                     length = 2 * _2M;
 913                 } else if (length > 4 * _2M) {
 914                     length = _2M;
 915                 } else if (length > 2 * _2M) {
 916                     length = _2M / 2;
 917                 } else if (length > _2M) {
 918                     length = _2M / 4;
 919                 } else {
 920                     length = 4096;
 921                 }
 922                 bytes = new byte[(int) length];
 923                 count = in.read(bytes);
 924                 output = concatArray(bytes, output);
 925                 length = in.available();
 926             }
 927         } catch (Exception ex) {
 928             ex.printStackTrace();
 929         } finally {
 930             if (null != in) {
 931                 try {
 932                     in.close();
 933                 } catch (Exception ex) {
 934                     ex.printStackTrace();
 935                 }
 936             }
 937         }
 938         return output;
 939     }
 940 
 941     /**
 942      * 合并数组
 943      *
 944      * @param old1
 945      * @param old2
 946      * @return
 947      */
 948     private static byte[] concatArray(byte[] old1, byte[] old2) {
 949         byte[] newArray = new byte[old1.length + old2.length];
 950         System.arraycopy(old1, 0, newArray, 0, old1.length);
 951         System.arraycopy(old2, 0, newArray, old1.length, old2.length);
 952         return newArray;
 953     }
 954 
 955     /**
 956      * dd 写入文件fullPath内容content
 957      *
 958      * @param filePath
 959      * @param fileName
 960      * @param content
 961      * @param isAppend
 962      */
 963     public static void dd(String filePath, String fileName, byte[] content, boolean isAppend) {
 964         try {
 965             String fullPath = combainPath(filePath, fileName);
 966             File file = new File(fullPath);
 967             FileTools.dd(file, content, isAppend);
 968         } catch (Exception ex) {
 969             ex.printStackTrace();
 970         }
 971     }
 972 
 973     /**
 974      * dd 写入文件fullPath内容content
 975      *
 976      * @param fullPath
 977      * @param content
 978      * @param isAppend
 979      */
 980     public static void dd(String fullPath, byte[] content, boolean isAppend) {
 981         try {
 982             File file = new File(fullPath);
 983             FileTools.dd(file, content, isAppend);
 984         } catch (Exception ex) {
 985             ex.printStackTrace();
 986         }
 987     }
 988 
 989     /**
 990      * dd 写入文件fullPath内容content
 991      *
 992      * @param file
 993      * @param content
 994      * @param isAppend
 995      */
 996     public static void dd(File file, byte[] content, boolean isAppend) {
 997         FileOutputStream fileOutputStream = null;
 998         try {
 999             if (!file.exists()) {
1000                 file.createNewFile();
1001             }
1002             fileOutputStream = new FileOutputStream(file, isAppend);
1003             fileOutputStream.write(content);
1004         } catch (Exception ex) {
1005             ex.printStackTrace();
1006         } finally {
1007             try {
1008                 if (null != fileOutputStream) {
1009                     fileOutputStream.close();
1010                 }
1011             } catch (IOException ex) {
1012                 ex.printStackTrace();
1013             }
1014         }
1015     }
1016 
1017     /**
1018      * write 写文件内容content到文件fullPath
1019      *
1020      * @param filePath
1021      * @param fileName
1022      * @param content
1023      */
1024     public static void write(String filePath, String fileName, String content) {
1025         try {
1026             String fullPath = combainPath(filePath, fileName);
1027             File file = new File(fullPath);
1028             FileTools.write(file, content, true);
1029         } catch (Exception ex) {
1030             ex.printStackTrace();
1031         }
1032     }
1033 
1034     /**
1035      * write 写文件内容content到文件fullPath
1036      *
1037      * @param fullPath
1038      * @param content
1039      */
1040     public static void write(String fullPath, String content) {
1041         try {
1042             File file = new File(fullPath);
1043             FileTools.write(file, content, true);
1044         } catch (Exception ex) {
1045             ex.printStackTrace();
1046         }
1047     }
1048 
1049     /**
1050      * write 写文件内容content到文件fullPath
1051      *
1052      * @param file
1053      * @param content
1054      */
1055     public static void write(File file, String content) {
1056         try {
1057             FileTools.write(file, content, true);
1058         } catch (Exception ex) {
1059             ex.printStackTrace();
1060         }
1061     }
1062 
1063     /**
1064      * write 写(追加)文件内容content到文件fullPath
1065      *
1066      * @param filePath
1067      * @param fileName
1068      * @param content
1069      * @param isAppend
1070      */
1071     public static void write(String filePath, String fileName, String content, boolean isAppend) {
1072         try {
1073             String fullPath = combainPath(filePath, fileName);
1074             File file = new File(fullPath);
1075             FileTools.write(file, content, isAppend);
1076         } catch (Exception ex) {
1077             ex.printStackTrace();
1078         }
1079     }
1080 
1081     /**
1082      * write 写(追加)文件内容content到文件fullPath
1083      *
1084      * @param fullPath
1085      * @param content
1086      * @param isAppend
1087      */
1088     public static void write(String fullPath, String content, boolean isAppend) {
1089         try {
1090             File file = new File(fullPath);
1091             FileTools.write(file, content, isAppend);
1092         } catch (Exception ex) {
1093             ex.printStackTrace();
1094         }
1095     }
1096 
1097     /**
1098      * write 写(追加)文件内容content到文件fullPath
1099      *
1100      * @param file
1101      * @param content
1102      * @param isAppend
1103      */
1104     public static void write(File file, String content, boolean isAppend) {
1105         FileWriter fileWriter = null;
1106         try {
1107             if (!file.exists()) {
1108                 file.createNewFile();
1109             }
1110             fileWriter = new FileWriter(file.getPath(), isAppend);
1111             fileWriter.write(content);
1112         } catch (Exception ex) {
1113             ex.printStackTrace();
1114         } finally {
1115             if (null != fileWriter) {
1116                 try {
1117                     fileWriter.close();
1118                 } catch (IOException ex) {
1119                     ex.printStackTrace();
1120                 }
1121             }
1122         }
1123     }
1124 
1125     /**
1126      * tail 添加文件内容content到文件的index位置
1127      *
1128      * @param filePath
1129      * @param fileName
1130      * @param content
1131      * @param index
1132      */
1133     public static void tail(String filePath, String fileName, String content, long index) {
1134         try {
1135             String fullPath = combainPath(filePath, fileName);
1136             File file = new File(fullPath);
1137             FileTools.tail(file, content, index);
1138         } catch (Exception ex) {
1139             ex.printStackTrace();
1140         }
1141     }
1142 
1143     /**
1144      * tail 添加文件内容content到文件的index位置
1145      *
1146      * @param fullPath
1147      * @param content
1148      * @param index
1149      */
1150     public static void tail(String fullPath, String content, long index) {
1151         try {
1152             File file = new File(fullPath);
1153             FileTools.tail(file, content, index);
1154         } catch (Exception ex) {
1155             ex.printStackTrace();
1156         }
1157     }
1158 
1159     /**
1160      * tail 添加文件内容content到文件的index位置
1161      *
1162      * @param file
1163      * @param content
1164      * @param index
1165      */
1166     public static void tail(File file, String content, long index) {
1167         RandomAccessFile randomAccessFile = null;
1168         try {
1169             if (!file.exists()) {
1170                 file.createNewFile();
1171             }
1172             randomAccessFile = new RandomAccessFile(file.getPath(), "rw");
1173             randomAccessFile.seek(index);
1174             randomAccessFile.writeBytes(content);
1175         } catch (Exception ex) {
1176             ex.printStackTrace();
1177         } finally {
1178             if (null != randomAccessFile) {
1179                 try {
1180                     randomAccessFile.close();
1181                 } catch (Exception ex) {
1182                     ex.printStackTrace();
1183                 }
1184             }
1185         }
1186     }
1187 
1188     /**
1189      * mkdir 创建目录
1190      *
1191      * @param filePath
1192      * @param fileName
1193      * @return
1194      */
1195     public static File mkdir(String filePath, String fileName) {
1196         File file = null;
1197         try {
1198             String fullPath = combainPath(filePath, fileName);
1199             file = new File(fullPath);
1200             file = mkdir(file);
1201         } catch (Exception ex) {
1202             ex.printStackTrace();
1203         }
1204         return file;
1205     }
1206 
1207     /**
1208      * mkdir 创建目录
1209      *
1210      * @param fullPath
1211      * @return
1212      */
1213     public static File mkdir(String fullPath) {
1214         File file = null;
1215         try {
1216             file = new File(fullPath);
1217             file = mkdir(file);
1218         } catch (Exception ex) {
1219             ex.printStackTrace();
1220         }
1221         return file;
1222     }
1223 
1224     /**
1225      * mkdir 创建目录
1226      *
1227      * @param file
1228      * @return
1229      */
1230     public static File mkdir(File file) {
1231         try {
1232             if (!file.exists()) {
1233                 file.mkdir();// 如果文件夹不存在则创建
1234             }
1235         } catch (Exception ex) {
1236             ex.printStackTrace();
1237         }
1238         return file;
1239     }
1240 
1241     /**
1242      * touch 创建文件
1243      *
1244      * @param filePath
1245      * @param fileName
1246      */
1247     public static void touch(String filePath, String fileName) {
1248         try {
1249             String fullPath = combainPath(filePath, fileName);
1250             File file = new File(fullPath);
1251             touch(file);
1252         } catch (Exception ex) {
1253             ex.printStackTrace();
1254         }
1255     }
1256 
1257     /**
1258      * touch 创建文件
1259      *
1260      * @param fullPath
1261      */
1262     public static void touch(String fullPath) {
1263         try {
1264             File file = new File(fullPath);
1265             touch(file);
1266         } catch (Exception ex) {
1267             ex.printStackTrace();
1268         }
1269     }
1270 
1271     /**
1272      * touch 创建文件
1273      *
1274      * @param file
1275      */
1276     public static void touch(File file) {
1277         try {
1278             if (!file.exists()) {
1279                 file.createNewFile();// 如果文件不存在则创建
1280             }
1281         } catch (Exception ex) {
1282             ex.printStackTrace();
1283         }
1284     }
1285 
1286     /**
1287      * rm 删除文件
1288      *
1289      * @param filePath
1290      * @param fileName
1291      */
1292     public static void rm(String filePath, String fileName) {
1293         try {
1294             String fullPath = combainPath(filePath, fileName);
1295             File file = new File(fullPath);
1296             rm(file);
1297         } catch (Exception ex) {
1298             ex.printStackTrace();
1299         }
1300     }
1301 
1302     /**
1303      * rm 删除文件
1304      *
1305      * @param fullPath
1306      */
1307     public static void rm(String fullPath) {
1308         try {
1309             File file = new File(fullPath);
1310             rm(file);
1311         } catch (Exception ex) {
1312             ex.printStackTrace();
1313         }
1314     }
1315 
1316     /**
1317      * rm 删除文件
1318      *
1319      * @param file
1320      */
1321     public static void rm(File file) {
1322         try {
1323             if (!file.exists()) {
1324                 throw new FileNotFoundException();
1325             }
1326             if (file.isFile()) {
1327                 file.delete();
1328             }
1329         } catch (Exception ex) {
1330             ex.printStackTrace();
1331         }
1332     }
1333 
1334     /**
1335      * rmdir 删除目录
1336      *
1337      * @param filePath
1338      * @param fileName
1339      * @param loop
1340      */
1341     public static void rmdir(String filePath, String fileName, boolean loop) {
1342         try {
1343             String fullPath = combainPath(filePath, fileName);
1344             File dir = new File(fullPath);
1345             rmdir(dir, loop);
1346         } catch (Exception ex) {
1347             ex.printStackTrace();
1348         }
1349     }
1350 
1351     /**
1352      * rmdir 删除目录
1353      *
1354      * @param fullPath
1355      * @param loop
1356      */
1357     public static void rmdir(String fullPath, boolean loop) {
1358         try {
1359             File dir = new File(fullPath);
1360             rmdir(dir, loop);
1361         } catch (Exception ex) {
1362             ex.printStackTrace();
1363         }
1364     }
1365 
1366     /**
1367      * rmdir 删除目录
1368      *
1369      * @param dir
1370      * @param loop
1371      */
1372     public static void rmdir(File dir, boolean loop) {
1373         try {
1374             if (!dir.exists()) {
1375                 throw new FileNotFoundException();
1376             }
1377             if (dir.isDirectory()) {
1378                 File[] files = dir.listFiles();
1379                 int length = files.length;
1380                 for (int i = 0; i < length && loop; i++) {
1381                     if (files[i].isDirectory()) {
1382                         rmdir(files[i], loop);
1383                     } else {
1384                         rm(files[i]);
1385                     }
1386                 }
1387                 if (loop || length == 0) {
1388                     dir.delete();
1389                 }
1390             }
1391         } catch (Exception ex) {
1392             ex.printStackTrace();
1393         }
1394     }
1395 
1396     /**
1397      * du 获取文件实际大小
1398      *
1399      * @param filePath
1400      * @param fileName
1401      * @param loop
1402      * @return
1403      */
1404     public static long du(String filePath, String fileName, boolean loop) {
1405         long size = 0;
1406         try {
1407             String fullPath = combainPath(filePath, fileName);
1408             File file = new File(fullPath);
1409             size = du(file, loop);
1410         } catch (Exception ex) {
1411             ex.printStackTrace();
1412         }
1413         return size;
1414     }
1415 
1416     /**
1417      * du 获取文件实际大小
1418      *
1419      * @param filePath
1420      * @param fileName
1421      * @return
1422      */
1423     public static long du(String filePath, String fileName) {
1424         long size = 0;
1425         try {
1426             String fullPath = combainPath(filePath, fileName);
1427             File file = new File(fullPath);
1428             size = du(file, false);
1429         } catch (Exception ex) {
1430             ex.printStackTrace();
1431         }
1432         return size;
1433     }
1434 
1435     /**
1436      * du 获取文件实际大小
1437      *
1438      * @param fullPath
1439      * @return
1440      */
1441     public static long du(String fullPath) {
1442         long size = 0;
1443         try {
1444             File file = new File(fullPath);
1445             size = du(file, false);
1446         } catch (Exception ex) {
1447             ex.printStackTrace();
1448         }
1449         return size;
1450     }
1451 
1452     /**
1453      * du 获取文件实际大小
1454      *
1455      * @param file
1456      * @return
1457      */
1458     public static long du(File file) {
1459         long size = 0;
1460         try {
1461             size = du(file, false);
1462         } catch (Exception ex) {
1463             ex.printStackTrace();
1464         }
1465         return size;
1466     }
1467 
1468     /**
1469      * du 获取文件实际大小
1470      *
1471      * @param fullPath
1472      * @param loop
1473      * @return
1474      */
1475     public static long du(String fullPath, boolean loop) {
1476         long size = 0;
1477         try {
1478             File file = new File(fullPath);
1479             size = du(file, loop);
1480         } catch (Exception ex) {
1481             ex.printStackTrace();
1482         }
1483         return size;
1484     }
1485 
1486     /**
1487      * du 获取文件实际大小
1488      *
1489      * @param file
1490      * @param loop
1491      * @return
1492      */
1493     public static long du(File file, boolean loop) {
1494         FileChannel fileChannel = null;
1495         long size = 0;
1496         try {
1497             if (!file.exists()) {
1498                 throw new FileNotFoundException();
1499             }
1500             if (file.isFile()) {
1501                 FileInputStream fis = new FileInputStream(file);
1502                 fileChannel = fis.getChannel();
1503                 size = fileChannel.size();
1504             } else if (file.isDirectory()) {
1505                 File[] files = file.listFiles();
1506                 int length = files.length;
1507                 for (int i = 0; i < length && loop; i++) {
1508                     if (files[i].isDirectory()) {
1509                         du(files[i], loop);
1510                     } else {
1511                         size += du(files[i], false);
1512                     }
1513                 }
1514             }
1515         } catch (Exception ex) {
1516             ex.printStackTrace();
1517         } finally {
1518             if (null != fileChannel) {
1519                 try {
1520                     fileChannel.close();
1521                 } catch (Exception ex) {
1522                     ex.printStackTrace();
1523                 }
1524             }
1525         }
1526         return size;
1527     }
1528 
1529     /**
1530      * 根据传入的文件夹目录返回目录下文件信息
1531      * 
1532      * @param path
1533      * @return fileCount:文件夹下压缩文件的个数,前台显示; files:压缩文件的list;
1534      *         fileNames:压缩文件夹的文件名,前台显示;
1535      *         fileInfoJson:包含fileCount、fileNames的json信息。
1536      */
1537     public static Map<String, Object> checkFolder(String path) {
1538         Map<String, Object> folderInfo = new HashMap<>();
1539         try {
1540             File file = new File(path);
1541             int fileCount = 0;
1542             List<File> files = new ArrayList<File>();
1543             List<String> fileNames = new ArrayList<>();
1544             if (!file.isDirectory()) {
1545                 return null;
1546             } else {
1547                 String[] fileList = file.list();
1548                 for (int i = 0; i < fileList.length; i++) {
1549                     if (fileList[i].lastIndexOf(".zip") > 0 || fileList[i].lastIndexOf(".rar") > 0) {
1550                         fileCount++;
1551                         File eleFile = new File(path + File.separator + fileList[i]);
1552                         files.add(eleFile);
1553                         fileNames.add(fileList[i]);
1554                     }
1555                 }
1556             }
1557             folderInfo.put("fileCount", fileCount);
1558             folderInfo.put("fileNames", fileNames);
1559             JSONObject jsonObject = JSONObject.fromObject(folderInfo);
1560             folderInfo.put("fileInfoJson", jsonObject.toString());
1561             folderInfo.put("files", files);
1562 
1563         } catch (Exception e) {
1564             // TODO: handle exception
1565         }
1566 
1567         return folderInfo;
1568     }
1569 
1570     /**
1571      * 文件上传
1572      * 
1573      * @param multipartRequest
1574      * @return
1575      */
1576     public static String uploadifyFiles(MultipartHttpServletRequest multipartRequest, String targetPath) {
1577         String responseStr = "";
1578         Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
1579         String configPath = File.separator;
1580         SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
1581         String year = sdf.format(new Date());
1582         configPath += year + File.separator;
1583         sdf = new SimpleDateFormat("MM");
1584         String month = sdf.format(new Date());
1585         configPath += month + File.separator;
1586         ContentID contentID = new ContentID(2L);
1587         long cid = contentID.nextId();
1588         configPath += cid + File.separator;
1589         targetPath += configPath;
1590         // 创建文件夹
1591         File file = new File(targetPath);
1592         if (!file.exists()) {
1593             file.mkdirs();
1594         }
1595         // 预留多文件上传,但流程需要另外改动
1596         for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
1597             // 上传文件名
1598             MultipartFile mf = entity.getValue();
1599             String fileName = mf.getOriginalFilename();
1600             // String fileExt = fileName.substring(fileName.lastIndexOf(".") +
1601             // 1).toLowerCase();
1602             // SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
1603             // String newFileName = df.format(new Date()) + "_" + new
1604             // Random().nextInt(1000) + "." + fileExt;
1605             responseStr = targetPath + fileName;
1606             File uploadFile = new File(targetPath + fileName);
1607             try {
1608                 mf.transferTo(uploadFile);
1609                 // FileCopyUtils.copy(mf.getBytes(), uploadFile);
1610             } catch (IOException e) {
1611                 responseStr = "error";
1612                 e.printStackTrace();
1613             }
1614         }
1615         return responseStr;
1616     }
1617 
1618     /**
1619      * 上传xsd文件,用户基础库建立时使用
1620      * 
1621      * @param multipartRequest
1622      * @param targetPath
1623      * @return
1624      */
1625     public static String uploadifyXsd(MultipartHttpServletRequest multipartRequest, String targetPath) {
1626         String responseStr = "";
1627         Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
1628         String configPath = File.separator;
1629         SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
1630         String docName = df.format(new Date()) + "_" + new Random().nextInt(1000);
1631         configPath += docName + File.separator;
1632         targetPath += configPath;
1633         // 创建文件夹
1634         File file = new File(targetPath);
1635         if (!file.exists()) {
1636             file.mkdirs();
1637         }
1638         // 预留多文件上传,但流程需要另外改动
1639         for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
1640             // 上传文件名
1641             MultipartFile mf = entity.getValue();
1642             String fileName = mf.getOriginalFilename();
1643             responseStr = targetPath + fileName;
1644             File uploadFile = new File(targetPath + fileName);
1645             try {
1646                 mf.transferTo(uploadFile);
1647                 // FileCopyUtils.copy(mf.getBytes(), uploadFile);
1648             } catch (IOException e) {
1649                 responseStr = "error";
1650                 e.printStackTrace();
1651             }
1652         }
1653         return responseStr;
1654     }
1655 
1656     /**
1657      * 上传企业资质
1658      * 
1659      * @param multipartRequest
1660      * @param targetPath
1661      * @return
1662      */
1663     public static String uploadifyCA(MultipartHttpServletRequest multipartRequest, String targetPath) {
1664         String responseStr = "";
1665         Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
1666         String configPath = File.separator;
1667         ContentID contentID = new ContentID(2L);
1668         long contentId = contentID.nextId();
1669         configPath += contentId + File.separator;
1670         targetPath += configPath;
1671         // 创建文件夹
1672         File file = new File(targetPath);
1673         if (!file.exists()) {
1674             file.mkdirs();
1675         }
1676         // 预留多文件上传,但流程需要另外改动
1677         for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
1678             // 上传文件名
1679             MultipartFile mf = entity.getValue();
1680             String fileName = mf.getOriginalFilename();
1681             responseStr = targetPath + fileName;
1682             File uploadFile = new File(targetPath + fileName);
1683             try {
1684                 mf.transferTo(uploadFile);
1685                 // FileCopyUtils.copy(mf.getBytes(), uploadFile);
1686             } catch (IOException e) {
1687                 responseStr = "error";
1688                 e.printStackTrace();
1689             }
1690         }
1691         return responseStr;
1692     }
1693 
1694     public static void uploadSimpleFile(CommonsMultipartFile file, String targetPath) {
1695         File targetFile = new File(targetPath).getParentFile();
1696         if (!targetFile.exists())
1697             targetFile.mkdirs();
1698         if (!file.isEmpty()) {
1699             try {
1700                 FileOutputStream fos = new FileOutputStream(targetPath);
1701                 InputStream in = file.getInputStream();
1702                 int b = 0;
1703                 while ((b = in.read()) != -1) {
1704                     fos.write(b);
1705                 }
1706                 fos.close();
1707                 in.close();
1708             } catch (Exception e) {
1709                 e.printStackTrace();
1710             }
1711         }
1712     }
1713 
1714     public static void inputstreamtofile(InputStream ins, File file) {
1715         OutputStream os;
1716         try {
1717             os = new FileOutputStream(file);
1718             int bytesRead = 0;
1719             byte[] buffer = new byte[8192];
1720             while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
1721                 os.write(buffer, 0, bytesRead);
1722             }
1723             os.close();
1724             ins.close();
1725 
1726         } catch (FileNotFoundException e) {
1727             // TODO Auto-generated catch block
1728             e.printStackTrace();
1729         } catch (IOException e) {
1730             // TODO Auto-generated catch block
1731             e.printStackTrace();
1732         }
1733     }
1734 
1735     /**
1736      * 删除过期的文件
1737      * 
1738      * @param file
1739      * @param save_days
1740      */
1741     public static void deleteOutOfDaysFiles(File file, int save_days) {
1742         if (file.exists()) {
1743             if (file.isDirectory()) {
1744                 // 2016 , 年
1745                 File[] files = file.listFiles();
1746                 if (files != null && files.length > 0) {
1747                     for (int i = 0; i < files.length; i++) {
1748                         try {
1749                             int days = DateUtil.daysBetween(new Date(file.lastModified()), new Date());
1750                             if (days > save_days) {
1751                                 if (files[i].isDirectory()) {
1752                                     FileTools.rmdir(files[i], true);
1753                                 } else {
1754                                     FileTools.rm(file);
1755                                 }
1756                             } else {
1757                                 // 11,月
1758                                 deleteOutOfDaysFiles(files[i], save_days);
1759                             }
1760                         } catch (ParseException e) {
1761                             // TODO Auto-generated catch block
1762                             e.printStackTrace();
1763                         }
1764                     }
1765                 }
1766             } else {
1767                 int days;
1768                 try {
1769                     days = DateUtil.daysBetween(new Date(file.lastModified()), new Date());
1770                     if (days > save_days) {
1771                         FileTools.rm(file);
1772                     }
1773                 } catch (ParseException e) {
1774                     // TODO Auto-generated catch block
1775                     e.printStackTrace();
1776                 }
1777 
1778             }
1779 
1780         }
1781     }
1782 
1783     public static List<File> getFileList(String strPath) {
1784 
1785         File dir = new File(strPath);
1786 
1787         File[] files = dir.listFiles();
1788         // 该文件目录下文件全部放入数组
1789         List<File> filelist = new ArrayList<>();
1790 
1791         if (files != null) {
1792             for (int i = 0; i < files.length; i++) {
1793                 String fileName = files[i].getName();
1794                 if (files[i].isDirectory()) { // 判断是文件还是文件夹
1795                     getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径
1796                 } else if (fileName.endsWith("avi")) { // 判断文件名是否以.avi结尾
1797 
1798                     filelist.add(files[i]);
1799                 } else {
1800                     continue;
1801                 }
1802             }
1803 
1804         }
1805         return filelist;
1806     }
1807 
1808     public static String shareFile(String sourcePath, String tarPath, String cid) {
1809 
1810         String toURL = tarPath;
1811 
1812         SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
1813         String year = sdf.format(new Date());
1814         toURL +=File.separator+ year + File.separator;
1815         sdf = new SimpleDateFormat("MM");
1816         String month = sdf.format(new Date());
1817         toURL += month + File.separator;
1818         String toRealUrl = toURL;
1819         File souceFile = new File(sourcePath);
1820         String str = "";
1821         if (souceFile.exists() && souceFile.isDirectory()) {
1822 
1823             str = sourcePath.substring(sourcePath.lastIndexOf(File.separator));
1824             toRealUrl = toRealUrl + File.separator + cid + File.separator;
1825 
1826         } else {
1827 
1828             String parentPath = souceFile.getParent();
1829             str = parentPath.substring(parentPath.lastIndexOf(File.separator));
1830             toRealUrl = toRealUrl + File.separator + cid + File.separator + str;
1831 
1832         }
1833 
1834         // 创建文件夹
1835         File file = new File(toRealUrl);
1836 
1837         if (!file.exists()) {
1838 
1839             file.mkdirs();
1840         }
1841 
1842         String newUrl = "";
1843 
1844         if (souceFile.exists() && souceFile.isDirectory()) {
1845 
1846             cutGeneralFile(sourcePath, file.getAbsolutePath());
1847             newUrl = file.getAbsolutePath() + File.separator + str;
1848 
1849         } else {
1850             
1851             if(souceFile.getName().toLowerCase().endsWith(".xml")){
1852                 
1853                 sourcePath=souceFile.getParent();
1854                 cutGeneralFile(sourcePath, file.getParent());
1855             }else{
1856             copyFile(sourcePath, file.getAbsolutePath());            
1857             }
1858             newUrl = file.getAbsolutePath() + File.separator + souceFile.getName();
1859         }
1860 
1861         return newUrl;
1862 
1863     }
1864 
1865     public static boolean shareFile2(String sourcePath, String tarPath) {
1866 
1867         String toURL = tarPath;
1868 
1869         File souceFile = new File(sourcePath);
1870 
1871         if (!new File(toURL).exists())
1872 
1873             new File(toURL).mkdirs();
1874 
1875         if (souceFile.exists() && souceFile.isDirectory()) {
1876 
1877             return cutGeneralFile(sourcePath, toURL);
1878 
1879         } else {
1880 
1881             File parentFile = souceFile.getParentFile();
1882             toURL = toURL + File.separator;
1883             copyFile(sourcePath, toURL);
1884             return true;
1885 
1886         }
1887 
1888     }
1889 
1890     /**
1891      * 获取不带扩展名的文件名
1892      * 
1893      * @param filename
1894      * @return
1895      */
1896     public static String getFileNameNoEx(String filename) {
1897 
1898         if ((filename != null) && (filename.length() > 0)) {
1899             int dot = filename.lastIndexOf('.');
1900             if ((dot > -1) && (dot < (filename.length()))) {
1901                 return filename.substring(0, dot);
1902             }
1903         }
1904         return filename;
1905     }
1906 
1907     // 获取文件的上上级目录
1908     public static String hPPPath(String file) {
1909 
1910         File fil = new File(file);
1911         String str = fil.getParent();
1912 
1913         File pfile = new File(str);
1914         String str2 = pfile.getParent();
1915         return str2;
1916     }
1917 
1918     // 获取文件的上级目录
1919     public static String hPPath(String file) {
1920 
1921         File fil = new File(file);
1922 
1923         return fil.getParent();
1924     }
1925 
1926     /**
1927      * 
1928      * @param file
1929      * @return
1930      */
1931     public static List<File> sortFileType(List<File> subList) {
1932 
1933         List<File> txtFile = new ArrayList<File>();
1934         List<File> docFile = new ArrayList<File>();
1935         List<File> pdfFile = new ArrayList<File>();
1936         List<File> xmlFile = new ArrayList<File>();
1937         List<File> htmlFile = new ArrayList<File>();
1938 
1939         List<File> filesAll = new ArrayList<File>();
1940 
1941         for (int i = 0; i < subList.size(); i++) {
1942 
1943             File file = subList.get(i);
1944 
1945             if (file.getAbsolutePath().contains(".txt")) {
1946 
1947                 txtFile.add(file);
1948 
1949             } else if (file.getAbsolutePath().contains(".doc") || file.getAbsolutePath().contains(".docx")) {
1950 
1951                 docFile.add(file);
1952 
1953             } else if (file.getAbsolutePath().contains(".pdf")) {
1954 
1955                 pdfFile.add(file);
1956 
1957             } else if (file.getName().contains(".xml")) {
1958 
1959                 xmlFile.add(file);
1960 
1961             } else if (file.getName().contains(".html")) {
1962 
1963                 htmlFile.add(file);
1964 
1965             }
1966 
1967         }
1968 
1969         if (txtFile.size() > 0) {
1970             filesAll.addAll(txtFile);
1971         }
1972         if (docFile.size() > 0) {
1973             filesAll.addAll(docFile);
1974         }
1975         if (pdfFile.size() > 0) {
1976             filesAll.addAll(pdfFile);
1977         }
1978         if (xmlFile.size() > 0) {
1979             filesAll.addAll(xmlFile);
1980         }
1981         if (htmlFile.size() > 0) {
1982             filesAll.addAll(htmlFile);
1983         }
1984 
1985         return filesAll;
1986     }
1987 
1988     /**
1989      * 复制文件或文件夹
1990      * 
1991      * @param srcPath
1992      * @param destDir
1993      *            目标文件所在的目录
1994      * @return
1995      */
1996     public static boolean copyGeneralFile(String srcPath, String destDir) {
1997 
1998         boolean flag = false;
1999         File file = new File(srcPath);
2000 
2001         if (!file.exists()) {
2002             return false;
2003         }
2004 
2005         if (file.isFile()) { // 源文件
2006             flag = copyFile(srcPath, destDir);
2007         } else if (file.isDirectory()) {
2008             flag = copyDirectory(srcPath, destDir);
2009         }
2010 
2011         return flag;
2012     }
2013 
2014     /**
2015      * 复制文件
2016      * 
2017      * @param srcPath
2018      *            源文件绝对路径
2019      * @param destDir
2020      *            目标文件所在目录
2021      * @return boolean
2022      */
2023     private static boolean copyFile(String srcPath, String destDir) {
2024         boolean flag = false;
2025 
2026         File srcFile = new File(srcPath);
2027 
2028         if (!srcFile.exists()) { // 源文件不存在
2029             return false;
2030         }
2031         // 获取待复制文件的文件名
2032         String fileName = srcPath.substring(srcPath.lastIndexOf(File.separator));
2033         String destPath = destDir + fileName;
2034         if (destPath.equals(srcPath)) { // 源文件路径和目标文件路径重复
2035             return false;
2036         }
2037 
2038         File destFile = new File(destPath);
2039 
2040         if (destFile.exists() && destFile.isFile()) { // 该路径下已经有一个同名文件
2041 
2042             //// 获取导入文件的文件名
2043             String srcStr = destPath.substring(0, destPath.indexOf("."));
2044 
2045             int i = 0;
2046 
2047             String destFileParent = destFile.getParent();
2048 
2049             // 获取目标的的所有文件
2050 
2051             List<File> files = getFiles(destFileParent, true);
2052 
2053             for (File file : files) {
2054 
2055                 // 获取每个文件的文件名
2056                 String destStr = file.getAbsolutePath().substring(0, file.getAbsolutePath().indexOf("."));
2057 
2058                 if (destStr.contains(srcStr)) {
2059 
2060                     i++;
2061                 }
2062             }
2063 
2064             // 获取要导入路径下的所有包含该文件名称的内容
2065             String str = srcPath.substring(srcPath.lastIndexOf(File.separator));
2066 
2067             StringBuilder fn = new StringBuilder(str);
2068 
2069             if (fileName.indexOf(".") > 0) {
2070 
2071                 fn.insert(fn.lastIndexOf("."), "_副本(" + i + ")");
2072 
2073             } else {
2074 
2075                 fn.append("_副本(" + i + ")");
2076             }
2077 
2078             destFile = new File(destDir + fn.toString());
2079 
2080             if (!destFile.exists()) {
2081 
2082                 try {
2083                     destFile.createNewFile();
2084                 } catch (IOException e) {
2085                     // TODO Auto-generated catch block
2086                     e.printStackTrace();
2087                 }
2088             }
2089 
2090         }
2091 
2092         File destFileDir = new File(destDir);
2093 
2094         destFileDir.mkdirs();
2095 
2096         try {
2097             FileInputStream fis = new FileInputStream(srcPath);
2098             FileOutputStream fos = new FileOutputStream(destFile);
2099             byte[] buf = new byte[1024];
2100             int c;
2101             while ((c = fis.read(buf)) != -1) {
2102                 fos.write(buf, 0, c);
2103             }
2104 
2105             fis.close();
2106             fos.close();
2107 
2108             flag = true;
2109         } catch (IOException e) {
2110             //
2111         }
2112 
2113         if (flag) {
2114         }
2115 
2116         return flag;
2117     }
2118 
2119     /**
2120      * 
2121      * @param srcPath
2122      *            源文件夹路径
2123      * @param destPath
2124      *            目标文件夹所在目录
2125      * @return
2126      */
2127     private static boolean copyDirectory(String srcPath, String destDir) {
2128         boolean flag = false;
2129 
2130         File srcFile = new File(srcPath);
2131         if (!srcFile.exists()) { // 源文件夹不存在
2132             return false;
2133         }
2134         // 获得待复制的文件夹的名字,比如待复制的文件夹为"E:\dir"则获取的名字为"dir"
2135         String dirName = new File(srcPath).getName();
2136         // String dirName = getDirName(srcPath);
2137         // 目标文件夹的完整路径
2138         String destPath = destDir + File.separator + dirName;
2139         // System.out.println("目标文件夹的完整路径为:" + destPath);
2140 
2141         if (destPath.equals(srcPath)) {
2142             return false;
2143         }
2144         File destDirFile = new File(destPath);
2145 
2146         if (!destDirFile.exists()) {
2147 
2148             destDirFile.mkdirs(); // 生成目录
2149 
2150         }
2151 
2152         File[] fileList = srcFile.listFiles(); // 获取源文件夹下的子文件和子文件夹
2153         if (fileList.length == 0) { // 如果源文件夹为空目录则直接设置flag为true,这一步非常隐蔽,debug了很久
2154             flag = true;
2155         } else {
2156             for (File temp : fileList) {
2157                 if (temp.isFile()) { // 文件
2158                     flag = copyFile(temp.getAbsolutePath(), destPath);
2159                 } else if (temp.isDirectory()) { // 文件夹
2160                     flag = copyDirectory(temp.getAbsolutePath(), destPath);
2161                 }
2162                 if (!flag) {
2163                     break;
2164                 }
2165             }
2166         }
2167 
2168         if (flag) {
2169         }
2170 
2171         return flag;
2172     }
2173 
2174     /**
2175      * 获取待复制文件夹的文件夹名
2176      * 
2177      * @param dir
2178      * @return String
2179      */
2180     private static String getDirName(String dir) {
2181         if (dir.endsWith(File.separator)) { // 如果文件夹路径以"\"结尾,则先去除末尾的"\"
2182             dir = dir.substring(0, dir.lastIndexOf(File.separator));
2183         }
2184         return dir.substring(dir.lastIndexOf(File.separator) + 1);
2185     }
2186 
2187     /**
2188      * 删除文件或文件夹
2189      * 
2190      * @param path
2191      *            待删除的文件的绝对路径
2192      * @return boolean
2193      */
2194     public static boolean deleteGeneralFile(String path) {
2195         boolean flag = false;
2196 
2197         File file = new File(path);
2198 
2199         if (!file.exists()) {
2200         }
2201 
2202         if (file.isDirectory()) { // 如果是目录,则单独处理
2203             flag = deleteDirectory(file.getAbsolutePath());
2204         } else if (file.isFile()) {
2205             flag = deleteFile(file);
2206         }
2207 
2208         if (flag) {
2209         }
2210 
2211         return flag;
2212     }
2213 
2214     /**
2215      * 删除文件
2216      * 
2217      * @param file
2218      * @return boolean
2219      */
2220     private static boolean deleteFile(File file) {
2221 
2222         return file.delete();
2223 
2224     }
2225 
2226     /**
2227      * 删除目录及其下面的所有子文件和子文件夹,注意一个目录下如果还有其他文件或文件夹
2228      * 则直接调用delete方法是不行的,必须待其子文件和子文件夹完全删除了才能够调用delete
2229      * 
2230      * @param path
2231      *            path为该目录的路径
2232      */
2233     private static boolean deleteDirectory(String path) {
2234         boolean flag = true;
2235         File dirFile = new File(path);
2236         if (!dirFile.isDirectory()) {
2237             return flag;
2238         }
2239         File[] files = dirFile.listFiles();
2240         for (File file : files) { // 删除该文件夹下的文件和文件夹
2241             // Delete file.
2242             if (file.isFile()) {
2243                 flag = deleteFile(file);
2244             } else if (file.isDirectory()) {// Delete folder
2245                 flag = deleteDirectory(file.getAbsolutePath());
2246             }
2247             if (!flag) { // 只要有一个失败就立刻不再继续
2248                 break;
2249             }
2250         }
2251         flag = dirFile.delete(); // 删除空目录
2252         return flag;
2253     }
2254 
2255     /**
2256      * 由上面方法延伸出剪切方法:复制+删除
2257      * 
2258      * @param destDir
2259      *            同上
2260      */
2261     public static boolean cutGeneralFile(String srcPath, String destDir) {
2262 
2263         if (!copyGeneralFile(srcPath, destDir)) {
2264             return false;
2265         }
2266 
2267         if (!deleteGeneralFile(srcPath)) {
2268             return false;
2269         }
2270 
2271         return true;
2272     }
2273 
2274     public static String[] getFileNameFromUrl(String url) {
2275         if (url != null && !url.equals("") && !url.equals("null")) {
2276             File file = new File(url);
2277             if (file.exists()) {
2278                 if (file.isDirectory()) {
2279                     return file.list();
2280                 } else if (file.isFile()) {
2281                     return new String[] { file.getName() };
2282                 }
2283             }
2284         }
2285         return null;
2286     }
2287 
2288     public static void deleteFileOrDirectory(String filePath) {
2289 
2290         File file = new File(filePath);
2291 
2292         if (file.exists()) {
2293             if (file.isDirectory()) {
2294 
2295                 rmdir(file, true);
2296 
2297             } else if (file.isFile()) {
2298 
2299                 if (filePath.equals(".xml") || filePath.equals(".html") || filePath.equals("htm")) {
2300 
2301                     rmdir(file.getParent(), true);
2302 
2303                 } else {
2304                     rm(file);
2305 
2306                 }
2307             }
2308         }
2309     }
2310 
2311     public static String getEnclosure(String filePath) {
2312 
2313         File sourceFile = new File(filePath);
2314 
2315         String tarPath = null;
2316         if (sourceFile.exists()) {
2317 
2318             if (sourceFile.isFile()) {
2319 
2320                 tarPath = getEnclosure(sourceFile.getParent());
2321 
2322             } else if (sourceFile.isDirectory()) {
2323 
2324                 tarPath = sourceFile.getParent();
2325 
2326             }
2327 
2328         }
2329         return tarPath;
2330 
2331     }
2332 
2333     public static int getFileCount(String filePath) {
2334 
2335         int count=0;
2336         File file = new File(filePath);
2337         File parentFile = null;
2338         if (file.isDirectory()) {
2339             parentFile = file;
2340         } else if (file.isFile()) {
2341             parentFile = file.getParentFile();
2342 
2343         }
2344 
2345         if (parentFile != null) {
2346 
2347             List<File> files=getFiles(parentFile, true);
2348 
2349             count=files.size();
2350         }
2351 
2352         return count;
2353     }
2354 
2355     // 获取文件夹的大小
2356     public static Long fileSize(String filePath) {
2357 
2358         long fileSize = 0l;
2359         File file = new File(filePath);
2360         File parentFile = null;
2361         if (file.isDirectory()) {
2362             parentFile = file;
2363         } else if (file.isFile()) {
2364             parentFile = file.getParentFile();
2365 
2366         }
2367 
2368         if (parentFile != null) {
2369 
2370             List<File> files=getFiles(parentFile, true);
2371 
2372             for (File f : files) {
2373 
2374                 if (f.exists() && f.isFile()) {
2375 
2376                     fileSize += f.length();
2377                 }
2378             }
2379         }
2380 
2381         return fileSize;
2382 
2383     }
2384 
2385     // 文件大小转化为 tb/mb/gb/tb
2386     public static String fileSizeToMB(long fileS) {
2387         String size = "";
2388         DecimalFormat df = new DecimalFormat("#.00");
2389         if (fileS < 1024) {
2390             size = df.format((double) fileS) + "BT";
2391         } else if (fileS < 1048576) {
2392             size = df.format((double) fileS / 1024) + "KB";
2393         } else if (fileS < 1073741824) {
2394             size = df.format((double) fileS / 1048576) + "MB";
2395         } else {
2396             size = df.format((double) fileS / 1073741824) + "GB";
2397         }
2398         return size;
2399 
2400     }
2401 
2402     public static void main(String[] args) {
2403 
2404     }
2405 
2406 }
原文地址:https://www.cnblogs.com/git-niu/p/7337529.html