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

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

希望这些代码能给大家带来些帮助,欢迎留言交流。

如有转载请标明出处   ,谢谢合作哦。


java实现基于关键字的文件夹(文件)的搜索、文件夹(文件)的复制、删除的更多相关文章

  1. java 弹出选择目录框(选择文件夹),获取选择的文件夹路径

    java 弹出选择目录框(选择文件夹),获取选择的文件夹路径 java 弹出选择目录框(选择文件夹),获取选择的文件夹路径:int result = 0;File file = null;String ...

  2. 键盘录入一个文件夹路径,统计该文件夹(包含子文件夹)中每种类型的文件及个数,注意:用文件类型(后缀名,不包含.(点),如:"java","txt")作为key, 用个数作为value,放入到map集合中,遍历map集合

    package cn.it.zuoye5; import java.io.File;import java.util.HashMap;import java.util.Iterator;import ...

  3. java实现批量修改指定文件夹下所有后缀名的文件为另外后缀名的代码

    java实现批量修改指定文件夹下所有后缀名的文件为另外后缀名的代码 作者:Vashon package com.ywx.batchrename; import java.io.File; import ...

  4. java:多层文件夹情况下,判断文件夹下是否有文件夹,并获取到没有文件夹的名字的方法

    业务问题案例 在公司遇到的一个问题,本以为很小很好解决,没想到花了一下午时间.图给的是文件路径,page1下有10个文件夹,每个有的有文件夹或者文件,要求得到page1下(即:123456789,10 ...

  5. JAVA中删除文件夹下及其子文件夹下的某类文件

    ##定时删除拜访图片 ##cron表达式 秒 分 时 天 月 ? ##每月1日整点执行 CRON1=0 0 0 1 * ? scheduled.enable1=false ##图片路径 filePat ...

  6. Android(java)学习笔记184:生成 4种 不同权限的文件

    1.首先我们编写一个生成 4种 不同权限的文件的程序案例: (1)首先是activity_main.xml文件: <RelativeLayout xmlns:android="http ...

  7. [sharepoint]rest api文档库文件上传,下载,拷贝,剪切,删除文件,创建文件夹,修改文件夹属性,删除文件夹,获取文档列表

    写在前面 最近对文档库的知识点进行了整理,也就有了这篇文章,当时查找这些接口,并用在实践中,确实废了一些功夫,也为了让更多的人走更少的弯路. 系列文章 sharepoint环境安装过程中几点需要注意的 ...

  8. Java项目生成可执行jar包、exe文件以及在Windows下的安装文件

    1.如何通过eclipse将Java项目生成可执行jar包 首先把在eclipse下的java项目导出jar file 下一步 下一步 下一步 最后点击完成,便生成了可执行的jar文件.可以在刚刚选择 ...

  9. JFinal中文件上传后会默认放置到WebContent的upload包下,但是tomcat会自动重启,当我们再次打开upload文件夹查看我们刚刚上传的文件时,发现上传的文件已经没有了。

    JFinal中文件上传后会默认放置到WebContent的upload包下,但是tomcat会自动重启,当我们再次打开upload文件夹查看我们刚刚上传的文件时,发现上传的文件已经没有了.因为tomc ...

随机推荐

  1. sql 经典面试题及答案(选课表)

    SQL数据库面试题以及答案 Student(Sno,Sname,Sage,Ssex) 学生表       Sno:学号:Sname:学生姓名:Sage:学生年龄:Ssex:学生性别Course(Cno ...

  2. SqlServer 全文索引指令大全(转载)

    -- 创建测试表 -- DROP TABLE FullTextIndexing CREATE TABLE FullTextIndexing ( ID ,) NOT NULL, Sentence VAR ...

  3. 【QT5】 第一个hello world 程序

    #include <QApplication> #include <QWidget> #include <QPushButton> int main(int arg ...

  4. 在Linux服务器上运行Jupyter notebook server教程

    在Linux服务器上运行Jupyter notebook server教程 很多deep learning教程都推荐在jupyter notebook运行python代码,方便及时交互.但只在本地运行 ...

  5. SDN2017 第五次实验作业

    实验目的 1.搭建如下拓扑并连接控制器 2.下发相关流表和组表实现负载均衡 3.抓包分析验证负载均衡 实验步骤 建立以下拓扑,并连接上ODL控制器. 利用ODL下发组表.流表,实现建议负载均衡 s1组 ...

  6. Docker 安装 - Docker 与前端(一)

    Docker 是一个开源的容器引擎,可以方便的对容器进行管理.作为一种新兴的虚拟化方式,跟传统的虚拟化方式相比具有众多优势.<Docker 遇见前端>系列文章,旨在记录如何通过 docke ...

  7. 【js】实现继承的6种方法

    1.原型链 基本思想:利用原型链让一个引用类型继承另一个引用类型的属性和方法. 让原型对象(B.prototype)等于另一个类型的实例(new A()), 即B.prototype = new A( ...

  8. Rx = Observables(响应) + LINQ(声明式语言) + Schedulers(异步)

    Reactive = Observables(响应)+ Schedulers(异步). Extensions = LINQ(语言集成查询) LINQ: The Operators of Reactiv ...

  9. HTTP 请求头中的 X-Forwarded-For,X-Real-IP

     X-Forwarded-For 在使用nginx做反向代理时,我们为了记录整个的代理过程,我们往往会在配置文件中做如下配置: location / { 省略... proxy_set_header ...

  10. find和find_if

    find函数 是在一个迭代器范围内查找特定元素得函数,可将将他用于任意容器类型得元素.这个函数返回的是所找元素得引用,如果没有找到元素就会返回这个容器得尾迭代器. #include <iostr ...