import org.apache.commons.io.IOUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
public class FileOperateUtil {
//删除文件夹
//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 = 0; 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;
}
/**
* 遍历文件夹中的所有文件放入list集合
*
*
*/
public static List<File> traverFolder(String path) {
ArrayList<File> arrayList = new ArrayList<File>();
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (files.length == 0) {
System.out.println("文件夹是空的!");
return null;
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println("文件夹:" + file2.getAbsolutePath());
traverFolder(file2.getAbsolutePath());
} else {
arrayList.add(new File(file2.getAbsolutePath()));
}
}
return arrayList;
}
} else {
System.out.println("文件不存在!");
return null;
}
}
/**
* 给客户端导出文件
* @param path
* @param fileName
* @param request
* @param response
*/
public static void fileOutput(String path, String fileName, HttpServletRequest request, HttpServletResponse response){
try{
//根据文件名获取 MIME 类型
String contentType = request.getServletContext().getMimeType(path);
fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
String contentDisposition = "attachment;filename="+fileName;
// 输入流
FileInputStream input = new FileInputStream(path);
// 设置头
response.setHeader("Content-Type",contentType);
response.setHeader("Content-Disposition",contentDisposition);
// 获取绑定了客户端的流
ServletOutputStream output = response.getOutputStream();
// 把输入流中的数据写入到输出流中
IOUtils.copy(input,output);
input.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
分享一个操作文件/文件夹的工具类,实现给客户端导出文件
猜你喜欢
转载自blog.csdn.net/XuYuanChong/article/details/90573385
今日推荐
周排行