zoukankan      html  css  js  c++  java
  • java实现基于关键字的文件夹(文件)的搜索、文件夹(文件)的复制、删除

      最近在做一个项目,需要实现这几项功能,上网查了很多资料,自己研究了好几天终于实现了,现在与大家分享一下。

    一、JAVA实现文件夹的搜索

      在百度搜索N个技术文章,从哪些大牛们共享的资料中终于写出了我想要的代码。成功实现了对文件夹的搜索。
      其原理是新定义个FileListener类使其实现ActionListener和Runnable接口。将其绑定在JButton上。在向FileListener的对象传入要搜索的文件夹名称时,会先列出系统所有盘符,并开启多个线程依次搜索各个盘符,其实现原理是先列出各个盘符的列表,用递归方式列出所有文件夹中的文件,当定位到文件绝对路径中含有该关键字时,会调用analysisPath解析路径,得到文件夹绝对路径。判断无误后停止所有线程,结束搜索。下面请看代码:
    import java.awt.event.ActionEvent;
    import java.io.File;
    
    public class FileListener implements java.awt.event.ActionListener, Runnable {
    
        private static String content;//确保一变化线程中即可调用
        private String root = "C:\";
        private static File[] listFile;//确保一变化线程中即可调用
        private String fileName;     //所需搜索问关键字
        private static String item = "";//通过item来判定执行run中的哪一个方法
        private Thread t;//统一设定线
        private static int count = 0;//统计出现的文件个数
        private FileListener fl;//控制线程的启动
        private static String s = "";//标识是否停止寻找
        private int threadNum = 0;
        private File[] rootlist;
        private int success = 0; //标识是否成功得到文件夹绝对路径
    
        public FileListener() {
    
        }
    
        public FileListener(String fileName, String root) {  
            this.root = root;
            this.fileName = fileName;
            File file1 = new File("");
            rootlist = file1.listRoots();  //获取所有盘符
        }
    
        public void actionPerformed(ActionEvent e) {
       //     System.out.println("响应事件");
            content = fileName;  //所需搜索的关键字
            if (e.getActionCommand().equals("Search")) {
                // 指定盘
                if (root == null || root.equals("")) {
                    System.out.println("该路径不存在!");
                    File file = new File("");
                    listFile = file.listRoots();
    
                } else {
                    if (content == null || content.length() == 0) {
    
                        File file = new File(root);
                        listFile = file.listFiles();
                        //启动线程
                        item = "search";
                        s = "";
                        fl = new FileListener(fileName, root);
    
                        t = new Thread(fl);
                        t.start();
    
                    } else {
    
                        //   String[] list;
                        int number = rootlist.length;
    		//list = new String[number];
    
                        //list[i] = rootlist[i].getAbsolutePath();
                        System.out.println("-------------------->" + rootlist[threadNum].getAbsolutePath());
                        File file = new File(rootlist[threadNum].getAbsolutePath());
                        listFile = file.listFiles();
                        //启动线程
                        item = "searchCount";
                        s = "";//每次线程启动前都要将s清空
                        fl = new FileListener(fileName, rootlist[threadNum].getAbsolutePath());
    //
                        t = new Thread(fl);
                        t.start();
    
                    }
                }
    
            }
        }
    
    
        private int search(File[] file) {
    
            //每次使用之前都将count清0,否则会叠加
            int count = 0;
            if (file == null || file.length == 0) {
                return 0;
            }
            for (int i = 0; i < file.length; i++) {
                File filenew = file[i];
                if (filenew.isDirectory()) {
                    File[] tempFile = filenew.listFiles();
                    count += search(tempFile);
                    this.count = count;
                }
                if (s.equals("stop")) {
                 
                    break;
                } else {
                    if (filenew.isFile()) {
                        count++;
         
                        s = "stop";
                  
                    }
                }
            }
    
            return count;
        }
    
        private int searchContent(File[] file) {
            int count = 0;
            if (file == null || file.length == 0) {
                return 0;
            }
            for (int i = 0; i < file.length; i++) {
                File filenew = file[i];
                // 包含字符
                if (filenew.isDirectory()) {
                    File[] tempFile = filenew.listFiles();
                    count += searchContent(tempFile);
                    this.count = count;
                }
    
                if (filenew.isFile()) {
                    String path = filenew.getAbsolutePath();
                    //找到与内容相符的路径
    
                    if (s.equals("stop")) {
                       
                        break;
                    } else {
    
                        if (path.indexOf(content) != -1) {
                            count++;
                          
                            s = "stop";
    
                         //   LeftPanel.ReturnPath = analysisPath(filenew.getAbsolutePath());     //此处为将搜索时检索的路径显示在JLabel上,用户体验更好。
                            if (analysisPath(filenew.getAbsolutePath())) {  
                                break;
                            }
                        }
                    }
                }
            }
    
            return count;
        }
    
        //重写run方法
        @Override
        public void run() {
    //		
    
            searchContent(listFile);
            System.out.println("searchContent函数结束");
            if (success == 0) {
                if (threadNum++ < rootlist.length) {
                    System.out.println("-------------------->" + rootlist[threadNum].getAbsolutePath());
                    File file = new File(rootlist[threadNum].getAbsolutePath());
                    listFile = file.listFiles();
                    //启动线程
                    item = "searchCount";
                    s = "";//每次线程启动前都要将s清空
                    fl = new FileListener(fileName, rootlist[threadNum].getAbsolutePath());
    //
                    t = new Thread(fl);
                    t.start();
                }
            }
    
        }
    
        /**
         * 解析搜索到的文件路径 得出目录文件绝对路径
         *
         * @param absolutePath
         * @return
         */
        private String analysisPath(String absolutePath) {//此处传入的absolutePath时定位到的路径中含有关键字的文件,,也就是目标文件夹中的文件。
            File f = new File(absolutePath);
    
            try {
                while (!f.getName().equals(fileName)) {  //此处是为了得到目标文件夹的绝对路径
                    f = f.getParentFile();   //得到父文件路径
                }
    
            } catch (Exception e) {
               System.out.println("未能成功检索到文件夹")
                s = "";
                return null;
            }
            System.out.println("成功检索到文件夹");
            success = 1;   //成功检索到文件夹 ,修改该变量值  使进程停止
    //fun(f.getAbsolutePath();)  //此处为您所需要处理该路径的方法,也可以把该值付给调用方的类成员变量得到该值
            return f.getAbsolutePath();
        }
    
    }
    
    
     

    二、JAVA实现文件夹的复制、删除


     在实现了文件夹搜索后,文件夹/文件的复制,删除相对简单些。下面我们来看代码:



    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JFrame;
    import static qqbackup.BackUpProgress.currentNum;
    //import static qqbackup.BackUpProgress.currentSize;
    
    class CopyFile {
    
        /**
         * 复制文件到目录 <功能详细描述>
         *
         * @param srcPath 文件绝对路径
         * @param destDirPath 目标文件夹绝对路径
         * @throws Exception
         * @see [类、类#方法、类#成员]
         */
        public static void copyFile(String srcPath, String destDirPath) throws Exception {
            File srcfile = new File(srcPath);
            File destDir = new File(destDirPath);
    
            InputStream is = null;
            OutputStream os = null;
            int ret = 0;
    
            // 源文件存在
            if (srcfile.exists() && destDir.exists() && destDir.isDirectory()) {
                try {
                    is = new FileInputStream(srcfile);
    
                    String destFile = destDirPath + File.separator + srcfile.getName();
    
                    os = new FileOutputStream(new File(destFile));
    
                    byte[] buffer = new byte[1024];
    
                    while ((ret = is.read(buffer)) != -1) {
                        os.write(buffer, 0, ret); // 此处不能用os.write(buffer),当读取最后的字节小于1024时,会多写;
                        // ret是读取的字节数
                    }
                    os.flush();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    throw new Exception("");
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new Exception("");
                } finally {
                    try {
                        if (os != null) {
                            os.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (Exception e) {
                    }
                }
            } else {
                throw new Exception("源文件不存在或目标路径不存在");
            }
    
        }
    
        /**
         * 列出文件夹下的所有文件,使用递归。 <功能详细描述>
         *
         * @param dirPath 文件夹绝对路径
         * @see [类、类#方法、类#成员]
         */
        public static void getFileList(String dirPath) {
            File rootDir = new File(dirPath);
            if (rootDir.exists()) {
                File[] files = rootDir.listFiles();
    
                for (File file : files) {
                    if (file.isDirectory()) {
                        System.out.println("目录" + file.getName());
                        // 递归调用
                        getFileList(file.getPath());
                    } else {
                        System.out.println("文件" + file.getName());
                    }
                }
            }
        }
    
        /**
         * <一句话功能简述>复制文件夹 <功能详细描述>
         *
         * @param srcDir 文件夹的绝对路径
         * @param destDir 目标绝对路径
         * @throws Exception
         * @see [类、类#方法、类#成员]
         */
        public static void copyFolder(String srcDir, String destDir) throws Exception {
            File srcFile = new File(srcDir);
    
            // 在目标路径建立文件夹
            String name = srcFile.getName();
            File destDirFile = new File(destDir);
                if (!destDirFile.exists()) {
                    destDirFile.mkdirs();   //如果路径不存在则创建文件夹
    
                }
            File destFile = new File(destDir + File.separator + name);  //目的文件夹内的元文件夹名称路径
            if (!destFile.exists()) {
                destFile.mkdir();             //如果路径不存在则创建文件夹
            }
            if (srcFile.exists() && destFile.isDirectory()) {
                File[] files = srcFile.listFiles();
    
                String src = srcDir;
                String dest = destFile.getAbsolutePath();
    
                for (File temp : files) {
                    // 复制目录
                    if (temp.isDirectory()) {
                        String tempSrc = src + File.separator + temp.getName();
                        String tempDest = dest + File.separator + temp.getName();
                        File tempFile = new File(tempDest);
                        if(!tempFile.exists()){
                        tempFile.mkdir();
                        }
                        // 当子目录不为空时
                        if (temp.listFiles().length != 0) {
                            // 递归调用
                            copyFolder(tempSrc, dest);
                        }
                    } else // 复制文件
                    {
                        String tempPath = src + File.separator + temp.getName();
                        copyFile(tempPath, dest);
                    }
                }
            }
            //  System.out.println("拷贝完成");
        }
    
        /**
         * 删除文件夹 <功能详细描述>
         * 要先删除子内容,再删除父内容
         *
         * @param dirPath 要删除的文件夹
         * @see [类、类#方法、类#成员]
         */
        public static void deleteFolder(String dirPath) {
            File folder = new File(dirPath);
            File[] files = folder.listFiles();
    
            for (File file : files) {
                if (file.isDirectory()) {
                    String tempFilePath = dirPath + File.separator + file.getName();
                    deleteFolder(tempFilePath);
                } else {
                    file.delete();
                }
    
            }
    
            folder.delete();
        }
    
    }
    


    希望这些代码能给大家带来些帮助,欢迎留言交流。
    如有转载请标明出处   ,谢谢合作哦。

    作者:郭耀华
    出处:http://www.guoyaohua.com
    微信:guoyaohua167
    邮箱:guo.yaohua@foxmail.com
    本文版权归作者和博客园所有,欢迎转载,转载请标明出处。
    【如果你觉得本文还不错,对你的学习带来了些许帮助,请帮忙点击右下角的推荐】

    dashang
  • 相关阅读:
    从0开始学习 GitHub 系列之「02.加入 GitHub」
    从0开始学习 GitHub 系列之「01.初识 GitHub
    用Redis轻松实现秒杀系统
    算法之美
    Android窗口管理服务WindowManagerService显示Activity组件的启动窗口(Starting Window)的过程分析
    6)django-示例(fbv)
    5)django-模板
    4)django-视图view
    3)django-路由系统url
    2)django-请求生命周期
  • 原文地址:https://www.cnblogs.com/guoyaohua/p/8502934.html
Copyright © 2011-2022 走看看