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();
    }

}


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

转载于:https://www.cnblogs.com/guoyaohua/p/8502934.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值