一、递归获取指定目录下的文件
public static List<File> getFilePaths(File parentPath) {
List<File> fileList = new ArrayList<>();
if (parentPath.isDirectory()) {
File[] files = parentPath.listFiles();
for (File file1 : Objects.requireNonNull(files)) {
fileList.addAll(getFilePaths(file1));
}
} else {
fileList.add(parentPath);
}
return fileList;
}
二、批量文件打包
public static String createZipAndReturnPath(List<File> fileList, String fileSaveRootPath, String zipName, boolean b) {
String zipPath = fileSaveRootPath + zipName;
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));) {
for (File file : fileList) {
String downloadPath = file.getAbsolutePath();
try (FileInputStream fis = new FileInputStream(downloadPath);) {
if (b) {
out.putNextEntry(new ZipEntry(file.getAbsolutePath().replace(fileSaveRootPath, "")));
} else {
out.putNextEntry(new ZipEntry(file.getName()));
}
int len;
byte[] buffer = new byte[8192];
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
out.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
out.close();
return zipPath;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
三、文件下载
public static void downloadFile(String sourcePath, String targetPath) throws Exception {
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(new File(sourcePath)));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(targetPath)));) {
byte[] buff = new byte[8192];
int len = 0;
while ((len = is.read(buff, 0, buff.length)) != -1) {
out.write(buff, 0, len);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
四、调用示例
public static void main(String[] args) throws Exception {
String basePath = "D:\\U盘\\文件\\教师文档\\";
List<File> filePaths = getFilePaths(new File(basePath));
filePaths.forEach(file -> System.out.println(file.getAbsolutePath()));
String zipAndReturnPath = createZipAndReturnPath(filePaths, basePath, "测试.zip", true);
downloadFile(zipAndReturnPath, basePath + "下载.zip");
}