Java operation file class (file decompression, file addition, deletion, modification and query)

From , 5 Years ago, written in Java, viewed 212 times.
URL https://pastebin.vip/view/28267ab8
  1. import java.io.File;
  2.  
  3. import java.io.FileInputStream;
  4.  
  5. import java.io.FileOutputStream;
  6.  
  7. import java.io.IOException;
  8.  
  9. import java.io.InputStream;
  10.  
  11. import java.util.Enumeration;
  12.  
  13. import org.apache.tools.zip.ZipEntry;
  14.  
  15. import org.apache.tools.zip.ZipFile;
  16.  
  17. import org.apache.tools.zip.ZipOutputStream;
  18.  
  19. import org.slf4j.Logger;
  20.  
  21. import org.slf4j.LoggerFactory;
  22.  
  23. /**
  24.  * 压缩,解压,删除,拷贝操作。
  25.  
  26.  * 注意:此类中用到的压缩类ZipEntry等都来自于org.apache.tools包而非java.util。此包在ant.jar中有。
  27.  *
  28.  * * @author Tony
  29.  */
  30.  
  31. public class FileUtil {
  32.  
  33.     protected static Logger log = LoggerFactory.getLogger(FileUtil.class);
  34.  
  35.     /**
  36.      *
  37.      * 压缩文件
  38.      *
  39.      * @param inputFileName
  40.      *            要压缩的文件或文件夹路径,例如:c:\\a.txt,c:\\a\
  41.      *
  42.      * @param outputFileName
  43.      *            输出zip文件的路径,例如:c:\\a.zip
  44.      *
  45.      */
  46.  
  47.     public static void zip(String inputFileName, String outputFileName)
  48.     throws Exception {
  49.  
  50.                     outputFileName));
  51.  
  52.         zip(out, new File(inputFileName), "");
  53.  
  54.         log.debug("压缩完成!");
  55.  
  56.         out.closeEntry();
  57.  
  58.         out.close();
  59.  
  60.     }
  61.  
  62.     /**
  63.      *
  64.      * 压缩文件
  65.      *
  66.      * @param out
  67.      *            org.apache.tools.zip.ZipOutputStream
  68.      *
  69.      * @param file
  70.      *            待压缩的文件
  71.      *
  72.      * @param base
  73.      *            压缩的根目录
  74.      *
  75.      */
  76.  
  77.     private static void zip(ZipOutputStream out, File file, String base)
  78.     throws Exception {
  79.  
  80.         if (file.isDirectory()) {
  81.  
  82.             File[] fl = file.listFiles();
  83.  
  84.             base = base.length() == 0 ? "" : base + File.separator;
  85.  
  86.             for (int i = 0; i < fl.length; i++) {
  87.  
  88.                 zip(out, fl[i], base + fl[i].getName());
  89.  
  90.             }
  91.  
  92.         } else {
  93.  
  94.             out.putNextEntry(new ZipEntry(base));
  95.  
  96.             log.debug("添加压缩文件:" + base);
  97.  
  98.             FileInputStream in = new FileInputStream(file);
  99.  
  100.             int b;
  101.  
  102.             while ((b = in.read()) != -1) {
  103.  
  104.                 out.write(b);
  105.  
  106.             }
  107.  
  108.             in.close();
  109.  
  110.         }
  111.  
  112.     }
  113.  
  114.     /**
  115.      *
  116.      * 解压zip文件
  117.      *
  118.      * @param zipFileName
  119.      *            待解压的zip文件路径,例如:c:\\a.zip
  120.      *
  121.      * @param outputDirectory
  122.      *            解压目标文件夹,例如:c:\\a\
  123.      *
  124.      */
  125.  
  126.     public static void unZip(String zipFileName, String outputDirectory)
  127.     throws Exception {
  128.  
  129.         ZipFile zipFile = new ZipFile(zipFileName);
  130.  
  131.         try {
  132.  
  133.             Enumeration<?> e = zipFile.getEntries();
  134.  
  135.             ZipEntry zipEntry = null;
  136.  
  137.             createDirectory(outputDirectory, "");
  138.  
  139.             while (e.hasMoreElements()) {
  140.  
  141.                 zipEntry = (ZipEntry) e.nextElement();
  142.  
  143.                 log.debug("解压:" + zipEntry.getName());
  144.  
  145.                 if (zipEntry.isDirectory()) {
  146.  
  147.                     String name = zipEntry.getName();
  148.  
  149.                     name = name.substring(0, name.length() - 1);
  150.  
  151.                     File f = new File(outputDirectory + File.separator + name);
  152.  
  153.                     f.mkdir();
  154.  
  155.                     log
  156.                     .debug("创建目录:" + outputDirectory + File.separator
  157.                            + name);
  158.  
  159.                 } else {
  160.  
  161.                     String fileName = zipEntry.getName();
  162.  
  163.                     fileName = fileName.replace('\\', '/');
  164.  
  165.                     if (fileName.indexOf("/") != -1) {
  166.  
  167.                         createDirectory(outputDirectory, fileName.substring(0,
  168.                                         fileName.lastIndexOf("/")));
  169.  
  170.                         fileName = fileName.substring(
  171.                                        fileName.lastIndexOf("/") + 1, fileName
  172.                                        .length());
  173.  
  174.                     }
  175.  
  176.                     File f = new File(outputDirectory + File.separator
  177.                                       + zipEntry.getName());
  178.  
  179.                     f.createNewFile();
  180.  
  181.                     InputStream in = zipFile.getInputStream(zipEntry);
  182.  
  183.                     FileOutputStream out = new FileOutputStream(f);
  184.  
  185.                     byte[] by = new byte[1024];
  186.  
  187.                     int c;
  188.  
  189.                     while ((c = in.read(by)) != -1) {
  190.  
  191.                         out.write(by, 0, c);
  192.  
  193.                     }
  194.  
  195.                     in.close();
  196.  
  197.                     out.close();
  198.  
  199.                 }
  200.  
  201.             }
  202.  
  203.         } catch (Exception ex) {
  204.  
  205.             System.out.println(ex.getMessage());
  206.  
  207.         } finally {
  208.  
  209.             zipFile.close();
  210.  
  211.             log.debug("解压完成!");
  212.  
  213.         }
  214.  
  215.     }
  216.     /**
  217.      * 功能描述:列出某文件夹及其子文件夹下面的文件,并可根据扩展名过滤
  218.      *
  219.      * @param path
  220.      *            文件
  221.      */
  222.     public static void list(File path) {
  223.         if (!path.exists()) {
  224.             System.out.println("文件名称不存?");
  225.         } else {
  226.             if (path.isFile()) {
  227.                 if (path.getName().toLowerCase().endsWith(".pdf")
  228.                         || path.getName().toLowerCase().endsWith(".doc")
  229.                         || path.getName().toLowerCase().endsWith(".chm")
  230.                         || path.getName().toLowerCase().endsWith(".html")
  231.                         || path.getName().toLowerCase().endsWith(".htm")) {// 文件格式
  232.                     System.out.println(path);
  233.                     System.out.println(path.getName());
  234.                 }
  235.             } else {
  236.                 File[] files = path.listFiles();
  237.                 for (int i = 0; i < files.length; i++) {
  238.                     list(files[i]);
  239.                 }
  240.             }
  241.         }
  242.     }
  243.     /**
  244.      *
  245.      * @param directory
  246.      * @param subDirectory
  247.      */
  248.     private static void createDirectory(String directory, String subDirectory) {
  249.  
  250.         String dir[];
  251.  
  252.         File fl = new File(directory);
  253.  
  254.         try {
  255.  
  256.             if (subDirectory == "" && fl.exists() != true) {
  257.  
  258.                 fl.mkdir();
  259.  
  260.             } else if (subDirectory != "") {
  261.  
  262.                 dir = subDirectory.replace('\\', '/').split("/");
  263.  
  264.                 for (int i = 0; i < dir.length; i++) {
  265.  
  266.                     File subFile = new File(directory + File.separator + dir[i]);
  267.  
  268.                     if (subFile.exists() == false)
  269.  
  270.                         subFile.mkdir();
  271.  
  272.                     directory += File.separator + dir[i];
  273.  
  274.                 }
  275.  
  276.             }
  277.  
  278.         } catch (Exception ex) {
  279.  
  280.             System.out.println(ex.getMessage());
  281.  
  282.         }
  283.  
  284.     }
  285.  
  286.     /**
  287.      *
  288.      * 拷贝文件夹中的所有文件到另外一个文件夹
  289.      *
  290.      * @param srcDirector
  291.      *            源文件夹
  292.      *
  293.      * @param desDirector
  294.      *            目标文件夹
  295.      *
  296.      */
  297.  
  298.     public static void copyFileWithDirector(String srcDirector,
  299.                                             String desDirector) throws IOException {
  300.  
  301.         (new File(desDirector)).mkdirs();
  302.  
  303.         File[] file = (new File(srcDirector)).listFiles();
  304.  
  305.         for (int i = 0; i < file.length; i++) {
  306.  
  307.             if (file[i].isFile()) {
  308.  
  309.                 log.debug("拷贝:" + file[i].getAbsolutePath() + "-->"
  310.                           + desDirector + "/" + file[i].getName());
  311.  
  312.                 FileInputStream input = new FileInputStream(file[i]);
  313.  
  314.                 FileOutputStream output = new FileOutputStream(desDirector
  315.                         + "/" + file[i].getName());
  316.  
  317.                 byte[] b = new byte[1024 * 5];
  318.  
  319.                 int len;
  320.  
  321.                 while ((len = input.read(b)) != -1) {
  322.  
  323.                     output.write(b, 0, len);
  324.  
  325.                 }
  326.  
  327.                 output.flush();
  328.  
  329.                 output.close();
  330.  
  331.                 input.close();
  332.  
  333.             }
  334.  
  335.             if (file[i].isDirectory()) {
  336.  
  337.                 log.debug("拷贝:" + file[i].getAbsolutePath() + "-->"
  338.                           + desDirector + "/" + file[i].getName());
  339.  
  340.                 copyFileWithDirector(srcDirector + "/" + file[i].getName(),
  341.                                      desDirector + "/" + file[i].getName());
  342.  
  343.             }
  344.  
  345.         }
  346.  
  347.     }
  348.  
  349.     /**
  350.      *
  351.      * 删除文件夹
  352.      *
  353.      * @param folderPath
  354.      *            folderPath 文件夹完整绝对路径
  355.      *
  356.      */
  357.  
  358.     public static void delFolder(String folderPath) throws Exception {
  359.  
  360.         // 删除完里面所有内容
  361.  
  362.         delAllFile(folderPath);
  363.  
  364.         String filePath = folderPath;
  365.  
  366.         filePath = filePath.toString();
  367.  
  368.         File myFilePath = new File(filePath);
  369.  
  370.         // 删除空文件夹
  371.  
  372.         myFilePath.delete();
  373.  
  374.     }
  375.  
  376.     /**
  377.      *
  378.      * 删除指定文件夹下所有文件
  379.      *
  380.      * @param path
  381.      *            文件夹完整绝对路径
  382.      *
  383.      */
  384.  
  385.     public static boolean delAllFile(String path) throws Exception {
  386.  
  387.         boolean flag = false;
  388.  
  389.         File file = new File(path);
  390.  
  391.         if (!file.exists()) {
  392.  
  393.             return flag;
  394.  
  395.         }
  396.  
  397.         if (!file.isDirectory()) {
  398.  
  399.             return flag;
  400.  
  401.         }
  402.  
  403.         String[] tempList = file.list();
  404.  
  405.         File temp = null;
  406.  
  407.         for (int i = 0; i < tempList.length; i++) {
  408.  
  409.             if (path.endsWith(File.separator)) {
  410.  
  411.                 temp = new File(path + tempList[i]);
  412.  
  413.             } else {
  414.  
  415.                 temp = new File(path + File.separator + tempList[i]);
  416.  
  417.             }
  418.  
  419.             if (temp.isFile()) {
  420.  
  421.                 temp.delete();
  422.  
  423.             }
  424.  
  425.             if (temp.isDirectory()) {
  426.  
  427.                 // 先删除文件夹里面的文件
  428.  
  429.                 delAllFile(path + "/" + tempList[i]);
  430.  
  431.                 // 再删除空文件夹
  432.  
  433.                 delFolder(path + "/" + tempList[i]);
  434.  
  435.                 flag = true;
  436.  
  437.             }
  438.  
  439.         }
  440.  
  441.         return flag;
  442.  
  443.     }
  444.     /**
  445.      * @param args
  446.      */
  447.     public static void main(String[] args) {
  448.         // TODO Auto-generated method stub
  449.         File file = new File("H:\\");
  450.         list(file);
  451.     }
  452. }

Reply to "Java operation file class (file decompression, file addition, deletion, modification and query)"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website