Java:<获取>、<删除>指定文件夹及里面所有文件
2024-08-29 14:56:36
工具类代码如下:
一、获取
public Class Test{ //定义全局变量,存放所有文件夹下的文档
List<String> fileList ; public List<String> getFileLists() { String path = "路径";
//用的时候再new,相当于用之前清空一下List
fileList = new ArrayList<String>(); List<String> list = getFileListsByPath(path); return list;
} public List<String> getFileListsByPath(String path) { File file = new File(path);
if(file.exists()){
File[] files = file.listFiles();
for(File file2 : files){
//若是文件夹,递归调用,往下继续遍历
if(file2.isDirectory()){
//遍历子文件夹的绝对路径下的所有文件
getFileListsByPath(file2.getAbsolutePath());
}else{
//若是文档,非文件夹,加入List
fileList.add(file2.getAbsolutePath());
}
} }
return fileList; } }
二、删除
/*
* 删除指定文件夹及里面所有文件
*/
import java.io.File; public class RemoveDirectoryUtil { //获得绝对路径:/D:/eclipse/workspace/项目名称/WebContent/WEB-INF/classes/
public final static String HOME_PATH = RemoveDirectoryUtil.class.getResource("/").getPath();
//获得绝对路径:/D:/eclipse/workspace/项目名称/WebContent/下的其他目录
public final static String FILE_PATH = HOME_PATH.subSequence(, HOME_PATH.indexOf("WEB-INF")) + "file/"; //删除文件夹
//param folderPath 文件夹完整绝对路径 public static void delFolder(String folderPath) {
try {
delAllFile(folderPath); //删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //删除空文件夹
} catch (Exception e) {
e.printStackTrace();
}
} //删除指定文件夹下所有文件
//param path 文件夹完整绝对路径
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = ; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);//再删除空文件夹
flag = true;
}
}
return flag;
} }
获取文件所在路径:
RemoveDirectoryUtil.FILE_PATH
(根据需要修改即可)
最后
只需要在方法里调用即可:
RemoveDirectoryUtil.delFolder("你的文件夹所在路径");
最新文章
- windows server 2012 FTP SMB 文件夹权限继承
- ubuntu 安装mysql
- 51nod-1661 1661 黑板上的游戏(组合游戏)
- Delphi XE的firemonkey获取当前文件所在路径的方法
- dota监测
- 修改jquery的remote让前段显示服务器错误信息
- 基于HTML5 Canvas的3D动态Chart图表
- windows 2008R2系统程序运行提示无法定位程序输入点ucrtbase.terminate
- C++primer笔记之关联容器
- Python+Selenium学习--alert/confirm/prompt 处理
- Python 学习第一章
- python正则表达式3-模式匹配
- 【Acm】算法之美—Jugs
- Selenium (4) —— Selenium是什么? WebDriver是什么?做什么?(101 Tutorial)
- iOS 界面启动时,功能新特征显示
- 使用bcp工具对boost库裁剪
- HDU 5618 Jam&#39;s problem again (cdq分治+BIT 或 树状数组套Treap)
- mybaits中";#";和";$";的区别
- windows7下的64位redis安装简介
- C++小总结