目录
1. 背景
不是专业开发,但偶尔会写一些小工具或者代码,自然就成了传说中“百度代码”的具象人。记录一些在开发Java项目时,遇到的代码片段,方便自己也方便他人参考吧。
2.代码集合
1)片段一:批量下载文件
文件结构如下:
/path
-- file1
-- file2
@GetMapping("/download/files/{id}")
public CommonResult downloadFiles(@PathVariable("id") Integer id, HttpServletResponse response) throws IOException {
// 通过文件id查找文件的保存路径是否存在
FileEntity fileEntity = fileService.getFileById(id);
String file = fileEntity.getFileName(); // 用于后面创建下载文件的文件名
String path = fileEntity.getFilePath();
if (path.isEmpty()) {
return new CommonResult(400, "无文件地址");
}
// 遍历指定目录下的所有文件名
String[] fileNames = new String[]{};
File fileParentPath = new File(path);
if (fileParentPath.isDirectory()) {
fileNames = fileParentPath.list();
}
if (0 == fileNames.length) {
return new CommonResult(404, "无文件可下载");
}
// 将路径和文件名组合作为下载文件的文件路径
List<String> filePaths = new ArrayList<>();
for (String fileName : fileNames) {
filePaths.add(path + "\\\\" + fileName);
}
String downloadFilename = file + ".zip";
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(downloadFilename));
// 压缩文件
for (String filePath : filePaths) {
fileToZip(filePath, zipOutputStream);
}
zipOutputStream.close();
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(downloadFilename.getBytes("UTF-8"), "iso-8859-1"));
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream inputStream = new FileInputStream(downloadFilename);
IOUtils.copy(inputStream, outputStream);
inputStream.close();
File fileTempZip = new File(downloadFilename);
fileTempZip.delete();
return new CommonResult(200, "下载完成");
}
// 压缩文件
public void fileToZip(String filePath, ZipOutputStream zipOutputStream) throws IOException{
File file = new File(filePath);
String fileName = file.getName();
FileInputStream fileInputStream = new FileInputStream(filePath);
byte[] bufferArea = new byte[1024 * 10];
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream, 1024 * 10);
zipOutputStream.putNextEntry(new ZipEntry(fileName));
int length = 0;
while ((length = bufferedInputStream.read(bufferArea, 0 , 1024 * 10)) != -1) {
zipOutputStream.write(bufferArea, 0, length);
}
fileInputStream.close();
bufferedInputStream.close();
}
参考:
https://www.jb51.net/article/199498.htm
https://www.cnblogs.com/tenWood/p/7582436.html
https://blog.csdn.net/weixin_43368623/article/details/103815829
2)片段二:删除目录及目录下所有文件
找不到原有代码了,这里仅有参考文档
参考:
https://www.cnblogs.com/eczhou/archive/2012/01/16/2323431.html