您的位置:首页 > 其它

读取和删除指定文件夹下的全部文件

2017-03-03 17:25 302 查看
package com.smbea.utils.file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

/**
* 读取和删除指定文件夹下的全部文件
* @author hapday
* @date 2017年2月24日 @time 上午9:21:54
*/
public class ReadAllFileByFolder {

/**
* 读取某个文件夹下的所有文件
* @param folderAbsolutePath 文件夹的绝对路径
* @return 文件夹下的全部文件(含子文件夹下的文件)
*/
public static List<String> readAllFileByFolder(String folderAbsolutePath) {
if(StringUtils.isBlank(folderAbsolutePath)) {
return null;
}

File folderFile = new File(folderAbsolutePath);

if (!folderFile.isDirectory()) {	// 如果不是文件夹
System.out.println("此路径不是有效的文件夹!");
System.out.println("文件名:" + folderFile.getName());
System.out.println("path = " + folderFile.getPath());
System.out.println("绝对路径:" + folderFile.getAbsolutePath() + "\n");

return null;
}

List<String> resultList = new ArrayList<String>();	// 文件列表

String [] fileList = folderFile.list();		// 列出当前文件夹下的文件列表

for (int index = 0; index < fileList.length; index++) {
File readedFile = new File(folderAbsolutePath + File.separator + fileList[index]);

if (!readedFile.isDirectory()) {
System.out.println("文件名:" + readedFile.getName());
System.out.println("path = " + readedFile.getPath());
System.out.println("绝对路径:" + readedFile.getAbsolutePath() + "\n");

resultList.add(readedFile.getAbsolutePath());
} else {
readAllFileByFolder(folderAbsolutePath + File.separator + fileList[index]);		// 递归出子文件夹下的文件
}
}

return resultList;
}

/**
* 删除某个文件夹下的所有文件夹和文件
* @param folderAbsolutePath 文件夹的绝对路径
* @return -1 未做删除操作;0 删除失败;1 删除成功;
*/
public static byte deleteAllFileByFolder(String folderAbsolutePath) {
if(StringUtils.isBlank(folderAbsolutePath)) {
return -1;
}

File folderFile = new File(folderAbsolutePath);
if (!folderFile.isDirectory()) {
folderFile.delete();

return 1;
}

String [] readedFiles = folderFile.list();		// 读取到的文件列表

for (int index = 0; index < readedFiles.length; index++) {
File readFile = new File(folderAbsolutePath + File.separator + readedFiles[index]);

if (!readFile.isDirectory()) {
System.out.println("文件名:" + readFile.getName());
System.out.println("path = " + readFile.getPath());
System.out.println("绝对路径:" + readFile.getAbsolutePath() + "\n");

readFile.delete();

System.out.println("文件删除成功");
} else if (readFile.isDirectory()) {
deleteAllFileByFolder(folderAbsolutePath + File.separator + readedFiles[index]);	// 递归删除子文件夹下的全部文件
}
}

folderFile.delete();

return 1;
}

public static void main(String[] args) {
readAllFileByFolder("D:/develop");
}

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐