FileManager类的设计与实现

本文介绍了一个名为FileManager的Java类,该类实现了多种文件操作功能,包括文件复制、移动、删除、压缩、解压、分割和组合。类中包含如listAllFiles、copyFile、copyFiles、splitFile、mergeFile、deleteFile、deleteFiles、moveFile、moveFiles、compressFile和unCompressFile等方法,覆盖了单个文件和多层目录的处理。

在学习java之初就一直想着要自己封装一个文件管理的类,可以实现各种文件操作。
但是一直迟迟没有实现,然后我就作为一个“任务”给了小猫,让小猫去学习一些文件操作相关的知识,其实小猫挺认真的,并且也挺聪明,至少她花费的时间要比我花费的时间要短,而完成的内容要比我的好,下面这个是我在不同阶段经过三次修改和实现才完成的。


Java文件操作,共实现了文件复制(单个文件和多层目录文件),文件移动(单个文件和多层目录文件),文件删除(单个文件和多层目录文件),文件压缩(单个文件),文件解压(单个文件),文件分割(将一个大文件分割为若干个小文件),文件组合(将多个文件组合到一个文件中)。

Code:
  1. package ttstudy.io;   
  2. import java.io.*;   
  3. import java.util.*;   
  4. import java.util.zip.*;   
  5.   
  6. public class FileManager {   
  7.     private static ArrayList<File> lsFiles = new ArrayList<File>();   
  8.     private static FileInputStream fis = null;   
  9.     private static FileOutputStream fos = null;   
  10.     /**  
  11.      * list all files  
  12.      * @param path  
  13.      * @return ArrayList<File>  
  14.      * @throws FileNotFoundException  
  15.      */  
  16.     public static ArrayList<File> listAllFiles(String path) throws FileNotFoundException {   
  17.         File file = new File(path);   
  18.         File[] f = file.listFiles();   
  19.         for(int i=0; i<f.length; i++) {   
  20.             lsFiles.add(f[i]);   
  21.             //If the current file is a directory, Recursion listed catalogue of the files   
  22.             if(f[i].isDirectory()) {   
  23.                 listAllFiles(f[i].getAbsolutePath());   
  24.             }   
  25.         }   
  26.         return lsFiles;   
  27.     }   
  28.     /**  
  29.      * copy srcFile to desFile  
  30.      * @param srcFile  
  31.      * @param desFile  
  32.      * @throws FileNotFoundException  
  33.      */  
  34.     public static void copyFile(String srcFile, String desFile) throws FileNotFoundException, IOException {   
  35.         fis = new FileInputStream(new File(srcFile));   
  36.         fos = new FileOutputStream(new File(desFile));   
  37.         byte[] buf = new byte[1024];   
  38.         int len = 0;   
  39.         while((len=fis.read(buf)) != -1) {   
  40.             fos.write(buf, 0, len);   
  41.         }   
  42.         fos.close();   
  43.         fis.close();   
  44.     }   
  45.     /**  
  46.      * copy all files in srcFile to desFile  
  47.      * @param srcFile  
  48.      * @param desFile  
  49.      * @throws FileNotFoundException  
  50.      */  
  51.     public static void copyFiles(String srcFile, String desFile) throws FileNotFoundException, IOException {   
  52.         ArrayList<File> lsFiles = listAllFiles(srcFile);   
  53.         for(int i=0; i<lsFiles.size(); i++) {   
  54.             File curFile = lsFiles.get(i);   
  55.             if(curFile.isDirectory()) {   
  56.                 new File(desFile+curFile.getAbsolutePath().substring(srcFile.length())).mkdir();   
  57.             } else {   
  58.                 copyFile(curFile.getAbsolutePath(), new File(desFile+curFile.getAbsolutePath().substring(srcFile.length())).getAbsolutePath());   
  59.             }   
  60.         }   
  61.     }   
  62.     /**  
  63.      * Split a file into multiple files  
  64.      * @param srcFile  
  65.      * @param desDir   分割后文件存放的位置,是一个目录  
  66.      * @param n  
  67.      * @return  
  68.      * @throws FileNotFoundException  
  69.      */  
  70.     public static File[] splitFile(String srcFile, String desDir, int part) throws FileNotFoundException, IOException {   
  71.         File[] rsFile = new File[part];   
  72.         File f = new File(srcFile);   
  73.         long partLen = f.length()/part;     //part等分   
  74.         int perLen = 2;   
  75.         if(partLen > 1024) {   
  76.             perLen = 512;   
  77.         } else {   
  78.             perLen = 2;   
  79.         }   
  80.         byte[] buf = new byte[perLen];   
  81.         fis = new FileInputStream(f);   
  82.         for(int i=0; i<part; i++) {   
  83.             int pos = f.getName().lastIndexOf('.');   
  84.             File partFile = new File(desDir+"/"+f.getName().substring(0, pos)+(i+1)+f.getName().substring(pos));   
  85.             fos = new FileOutputStream(partFile);   
  86.             rsFile[i] = partFile;   
  87.             long m = partLen/perLen;   
  88.             for(int j=0; j<m; j++) {   
  89.                 int len = 0;   
  90.                 if((len=fis.read(buf)) != -1) {   
  91.                     fos.write(buf, 0, len);   
  92.                 }   
  93.             }   
  94.         }   
  95.         //由于整除原因,可能导致最后一部分没有写入到文件中,因此需要补充下面内容   
  96.         int nn= 0;   
  97.         if((nn=fis.read(buf)) != -1) {   
  98.             fos.write(buf, 0, nn);   
  99.         }   
  100.         fos.close();   
  101.         fis.close();   
  102.         return rsFile;   
  103.     }   
  104.     /**  
  105.      * Combination of multiple files into one file  
  106.      * @param srcFile  
  107.      * @param desFile  
  108.      * @return  
  109.      * @throws FileNotFoundException  
  110.      * @throws IOException  
  111.      */  
  112.     public static File mergeFile(File[] srcFile, String desFile) throws FileNotFoundException, IOException {   
  113.         File rsFile = new File(desFile);   
  114.         fos = new FileOutputStream(new File(desFile));   
  115.         byte[] buf = new byte[1024];   
  116.         int len = 0;   
  117.         for(int i=0; i<srcFile.length; i++) {   
  118.             fis = new FileInputStream(srcFile[i]);   
  119.             while((len=fis.read(buf)) != -1) {   
  120.                 fos.write(buf, 0, len);   
  121.             }   
  122.             fis.close();   
  123.         }   
  124.         if(fos != null) {   
  125.             fos.close();   
  126.         }   
  127.         if(fis != null) {   
  128.             fis.close();               
  129.         }   
  130.         return rsFile;   
  131.     }   
  132.     /**  
  133.      * delete a file  
  134.      * @param srcFile  
  135.      * @throws FileNotFoundException  
  136.      * @throws IOException  
  137.      */  
  138.     public static void deleteFile(String srcFile) throws FileNotFoundException, IOException {   
  139.         new File(srcFile).delete();   
  140.     }   
  141.     /**  
  142.      * Delete all files in srcFile,This is too difficult for me  
  143.      * @param srcFile  
  144.      * @throws FileNotFoundException  
  145.      * @throws IOException  
  146.      */  
  147.     public static void deleteFiles(String srcFile) throws FileNotFoundException, IOException {   
  148.         LinkedList<File> dirs = new LinkedList<File>();    
  149.         dirs.add(new File(srcFile));   
  150.         while(dirs.size() > 0){   
  151.             File currentDir = (File)dirs.getFirst();   
  152.             File[] files = currentDir.listFiles();   
  153.             boolean emptyDir = true;   
  154.             for(int i = 0 ;i < files.length;i++) {   
  155.                 if (files[i].isFile()) {   
  156.                     files[i].delete();   
  157.                 } else {   
  158.                     dirs.addFirst(files[i]);   
  159.                     emptyDir = false;   
  160.                 }   
  161.             }   
  162.             if (emptyDir){   
  163.                 currentDir.delete();   
  164.                 dirs.removeFirst();   
  165.             }   
  166.         }   
  167.     }   
  168.     /**  
  169.      * move srcFile to desFile  
  170.      * @param srcFile  
  171.      * @param desFile  
  172.      * @throws FileNotFoundException  
  173.      */  
  174.     public static void moveFile(String srcFile, String desFile) throws FileNotFoundException, IOException {   
  175.         copyFile(srcFile, desFile);   
  176.         new File(srcFile).delete();   
  177.     }   
  178.     /**  
  179.      * move srcFile to desFile  
  180.      * @param srcFile  
  181.      * @param desFile  
  182.      * @throws FileNotFoundException  
  183.      */  
  184.     public static void moveFiles(String srcFile, String desFile) throws FileNotFoundException, IOException {   
  185.         copyFiles(srcFile, desFile);   
  186.         deleteFiles(srcFile);   
  187.     }   
  188.     /**  
  189.      * compress files  
  190.      * @param srcFile  
  191.      * @param rarFile  
  192.      * @throws FileNotFoundException  
  193.      * @throws IOException  
  194.      */  
  195.     public static void compressFile(String _unZipFile, String _zipFile) throws FileNotFoundException, IOException {   
  196.         File srcFile = new File(_unZipFile);   
  197.         File zipFile = new File(_zipFile);   
  198.         DataInputStream dis = new DataInputStream(new FileInputStream(srcFile));   
  199.         if(!zipFile.exists()) {   
  200.             File zipdir = new File(zipFile.getParent());   
  201.             if(!zipdir.exists()) {   
  202.                 zipdir.mkdirs();   
  203.             }   
  204.             zipFile.createNewFile();   
  205.         }   
  206.         ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));   
  207.         zos.setMethod(ZipOutputStream.DEFLATED);   
  208.         ZipEntry ze = new ZipEntry(srcFile.getName());   
  209.         zos.putNextEntry(ze);   
  210.         DataOutputStream dos = new DataOutputStream(zos);   
  211.            
  212.         byte[] buf = new byte[2048];   
  213.         int len=0;   
  214.         while((len=dis.read(buf)) != -1) {   
  215.             dos.write(buf, 0, len);   
  216.         }   
  217.         dos.close();   
  218.         dis.close();   
  219.     }   
  220.     /**  
  221.      * uncompress files  
  222.      * @param rarFile  
  223.      * @param srcFile  
  224.      * @throws FileNotFoundException  
  225.      * @throws IOException  
  226.      */  
  227.     @SuppressWarnings("unchecked")   
  228.     public static void unCompressFile(String _zipFile, String _unZipDir) throws FileNotFoundException, IOException {   
  229.         File unZipFile = new File("_unZipFile");   
  230.         if(! unZipFile.exists()) {   
  231.             unZipFile.mkdirs();   
  232.         }   
  233.         ZipEntry ze = null;   
  234.         ZipFile zf = new ZipFile(new File(_zipFile));   
  235.         Enumeration<ZipEntry> en = (Enumeration<ZipEntry>)zf.entries();   
  236.         if(en.hasMoreElements()) {   
  237.             ze = (ZipEntry)en.nextElement();   
  238.         }   
  239.         unZipFile = new File(_unZipDir+File.separator+ze.getName());   
  240.         if(! unZipFile.exists()) {   
  241.             unZipFile.createNewFile();   
  242.         }   
  243.         DataInputStream dis = new DataInputStream(zf.getInputStream(ze));   
  244.         DataOutputStream dos = new DataOutputStream(new FileOutputStream(unZipFile));   
  245.         int len = 0;   
  246.         byte[] buf = new byte[2048];   
  247.         while((len=dis.read(buf)) != -1) {   
  248.             dos.write(buf, 0, len);   
  249.         }   
  250.         dos.close();   
  251.         dis.close();   
  252.     }   
  253.     /**  
  254.      *   
  255.      * @param args  
  256.      */  
  257.     public static void main(String[] args) throws FileNotFoundException, IOException {   
  258.         //          ArrayList<File> lsFiles = listAllFiles("D:/temp");   
  259.         //          for(int i=0; i<lsFiles.size(); i++) {   
  260.         //              System.out.println(lsFiles.get(i).getPath());   
  261.         //          }   
  262.         //          System.out.println(lsFiles.size());   
  263.         //          //copyFile("D:/temp/我的桌面.jpg","D:/temp/test.jpg");   
  264.         //          try {   
  265.         //              copyFiles("D:/temp","D:/tt");   
  266.         //          } catch (IOException e) {   
  267.         //              // TODO Auto-generated catch block   
  268.         //              e.printStackTrace();   
  269.         //          }   
  270.         //          //moveFile("D:/temp/我的桌面.jpg","D:/temp/test.jpg");   
  271.                     //moveFiles("D:/ttt","D:/temp");   
  272.         //          File f = new File("D:/temp/软件0820   9308036    .王颜涛.doc");   
  273.         //          System.out.println(f.getName());   
  274. //      try {   
  275. //          splitFile("D:/temp/tttt.rar", "D:/temp/test", 3);   
  276. //      } catch (IOException e) {   
  277. //          e.printStackTrace();   
  278. //      }   
  279. //      File[] f = {new File("D:/temp/test/tttt1.rar"), new File("D:/temp/test/tttt2.rar"), new File("D:/temp/test/tttt3.rar")};   
  280. //      try {   
  281. //          mergeFile(f, "D:/temp/test.rar");   
  282. //      } catch (IOException e) {   
  283. //          // TODO Auto-generated catch block   
  284. //          e.printStackTrace();   
  285. //      }   
  286.         //deleteFiles("D:/temp/tttt");         
  287.         compressFile("D:/temp/bb.pdf","D:/temp/bb.rar");   
  288.         //unCompressFile("D:/temp/test.rar","D:/temp/test2");   
  289.     }   
  290. }  

 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值