读取某一目录下的所有文件以及文件内容 包括删除以及定时删除
This commit is contained in:
@@ -0,0 +1,320 @@
|
||||
package com.klp.controller;
|
||||
|
||||
import com.klp.domain.vo.ApiResponseVo;
|
||||
import com.klp.domain.FileInfo;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 文件管理控制器
|
||||
* 提供文件读取、删除和定时删除功能
|
||||
*/
|
||||
@Controller
|
||||
@RequestMapping("/wms/file")
|
||||
public class WmsFileManagementController {
|
||||
|
||||
// 文件目录路径
|
||||
private static final String DIRECTORY_PATH = "testDirectory";
|
||||
|
||||
/**
|
||||
* 获取目录下所有文件信息
|
||||
* GET /api/file/list
|
||||
*/
|
||||
@GetMapping("/list")
|
||||
@ResponseBody
|
||||
public ResponseEntity<ApiResponseVo<List<FileInfo>>> getAllFiles() {
|
||||
try {
|
||||
Path directory = Paths.get(DIRECTORY_PATH);
|
||||
|
||||
// 检查目录是否存在
|
||||
if (!Files.exists(directory)) {
|
||||
return ResponseEntity.ok(new ApiResponseVo<>(false, "目录不存在: " + DIRECTORY_PATH, null));
|
||||
}
|
||||
|
||||
// 获取所有文件
|
||||
List<FileInfo> fileList = new ArrayList<>();
|
||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
|
||||
for (Path file : stream) {
|
||||
if (Files.isRegularFile(file)) {
|
||||
FileInfo fileInfo = readFileInfo(file);
|
||||
fileList.add(fileInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String message = String.format("成功获取 %d 个文件", fileList.size());
|
||||
return ResponseEntity.ok(new ApiResponseVo<>(true, message, fileList));
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMsg = "获取文件列表失败: " + e.getMessage();
|
||||
System.err.println(errorMsg);
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new ApiResponseVo<>(false, errorMsg, null));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件名删除文件
|
||||
* DELETE /api/file/delete/{fileName}
|
||||
*/
|
||||
@DeleteMapping("/delete/{fileName}")
|
||||
@ResponseBody
|
||||
public ResponseEntity<ApiResponseVo<String>> deleteFile(@PathVariable String fileName) {
|
||||
try {
|
||||
Path filePath = Paths.get(DIRECTORY_PATH, fileName);
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!Files.exists(filePath)) {
|
||||
return ResponseEntity.ok(new ApiResponseVo<>(false, "文件不存在: " + fileName, null));
|
||||
}
|
||||
|
||||
// 检查是否为普通文件
|
||||
if (!Files.isRegularFile(filePath)) {
|
||||
return ResponseEntity.ok(new ApiResponseVo<>(false, "不是普通文件: " + fileName, null));
|
||||
}
|
||||
|
||||
// 删除文件
|
||||
Files.delete(filePath);
|
||||
|
||||
String message = "文件删除成功: " + fileName;
|
||||
return ResponseEntity.ok(new ApiResponseVo<>(true, message, fileName));
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMsg = "删除文件失败: " + e.getMessage();
|
||||
System.err.println(errorMsg);
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new ApiResponseVo<>(false, errorMsg, null));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除文件
|
||||
* POST /api/file/batch-delete
|
||||
*/
|
||||
@PostMapping("/batch-delete")
|
||||
@ResponseBody
|
||||
public ResponseEntity<ApiResponseVo<Map<String, Object>>> batchDeleteFiles(@RequestBody List<String> fileNames) {
|
||||
try {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
List<String> successList = new ArrayList<>();
|
||||
List<String> failedList = new ArrayList<>();
|
||||
|
||||
for (String fileName : fileNames) {
|
||||
try {
|
||||
Path filePath = Paths.get(DIRECTORY_PATH, fileName);
|
||||
|
||||
if (Files.exists(filePath) && Files.isRegularFile(filePath)) {
|
||||
Files.delete(filePath);
|
||||
successList.add(fileName);
|
||||
} else {
|
||||
failedList.add(fileName + " (文件不存在)");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
failedList.add(fileName + " (" + e.getMessage() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
result.put("successCount", successList.size());
|
||||
result.put("failedCount", failedList.size());
|
||||
result.put("successFiles", successList);
|
||||
result.put("failedFiles", failedList);
|
||||
|
||||
String message = String.format("批量删除完成: 成功 %d 个, 失败 %d 个",
|
||||
successList.size(), failedList.size());
|
||||
|
||||
return ResponseEntity.ok(new ApiResponseVo<>(true, message, result));
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMsg = "批量删除失败: " + e.getMessage();
|
||||
System.err.println(errorMsg);
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new ApiResponseVo<>(false, errorMsg, null));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动执行定时删除(删除3个月前的文件)
|
||||
* POST /api/file/cleanup
|
||||
*/
|
||||
@PostMapping("/cleanup")
|
||||
@ResponseBody
|
||||
public ResponseEntity<ApiResponseVo<Map<String, Object>>> manualCleanup() {
|
||||
return performCleanup();
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时删除任务 - 每3个月执行一次
|
||||
* 删除3个月前的文件
|
||||
*/
|
||||
@Scheduled(cron = "0 0 2 1 */3 *") // 每3个月的第1天凌晨2点执行
|
||||
public void scheduledCleanup() {
|
||||
System.out.println("=== 开始执行定时删除任务 ===");
|
||||
System.out.println("执行时间: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
|
||||
ResponseEntity<ApiResponseVo<Map<String, Object>>> response = performCleanup();
|
||||
ApiResponseVo<Map<String, Object>> result = response.getBody();
|
||||
|
||||
if (result != null) {
|
||||
System.out.println("定时删除结果: " + result.getMessage());
|
||||
if (result.getData() != null) {
|
||||
Map<String, Object> data = result.getData();
|
||||
System.out.println("删除文件数量: " + data.get("deletedCount"));
|
||||
System.out.println("删除的文件: " + data.get("deletedFiles"));
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("=== 定时删除任务完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行清理操作
|
||||
*/
|
||||
private ResponseEntity<ApiResponseVo<Map<String, Object>>> performCleanup() {
|
||||
try {
|
||||
Path directory = Paths.get(DIRECTORY_PATH);
|
||||
|
||||
if (!Files.exists(directory)) {
|
||||
return ResponseEntity.ok(new ApiResponseVo<>(false, "目录不存在: " + DIRECTORY_PATH, null));
|
||||
}
|
||||
|
||||
// 计算3个月前的日期
|
||||
LocalDateTime threeMonthsAgo = LocalDateTime.now().minusMonths(3);
|
||||
|
||||
List<String> deletedFiles = new ArrayList<>();
|
||||
int deletedCount = 0;
|
||||
|
||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
|
||||
for (Path file : stream) {
|
||||
if (Files.isRegularFile(file)) {
|
||||
try {
|
||||
// 获取文件最后修改时间
|
||||
LocalDateTime fileModifiedTime = LocalDateTime.ofInstant(
|
||||
Files.getLastModifiedTime(file).toInstant(),
|
||||
java.time.ZoneId.systemDefault()
|
||||
);
|
||||
|
||||
// 如果文件修改时间早于3个月前,则删除
|
||||
if (fileModifiedTime.isBefore(threeMonthsAgo)) {
|
||||
Files.delete(file);
|
||||
deletedFiles.add(file.getFileName().toString());
|
||||
deletedCount++;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("删除文件失败: " + file.getFileName() + " - " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("deletedCount", deletedCount);
|
||||
result.put("deletedFiles", deletedFiles);
|
||||
result.put("cleanupTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
result.put("thresholdTime", threeMonthsAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
|
||||
String message = String.format("清理完成: 删除了 %d 个3个月前的文件", deletedCount);
|
||||
return ResponseEntity.ok(new ApiResponseVo<>(true, message, result));
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMsg = "清理操作失败: " + e.getMessage();
|
||||
System.err.println(errorMsg);
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new ApiResponseVo<>(false, errorMsg, null));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件信息
|
||||
*/
|
||||
private FileInfo readFileInfo(Path filePath) throws IOException {
|
||||
String fileName = filePath.getFileName().toString();
|
||||
String fileContent = readFileContent(filePath);
|
||||
long fileSize = Files.size(filePath);
|
||||
|
||||
LocalDateTime lastModified = LocalDateTime.ofInstant(
|
||||
Files.getLastModifiedTime(filePath).toInstant(),
|
||||
java.time.ZoneId.systemDefault()
|
||||
);
|
||||
String lastModifiedStr = lastModified.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||
|
||||
return new FileInfo(fileName, fileContent, fileSize, lastModifiedStr, filePath.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件内容
|
||||
*/
|
||||
private String readFileContent(Path filePath) throws IOException {
|
||||
try {
|
||||
// 尝试使用UTF-8编码读取
|
||||
return new String(Files.readAllBytes(filePath), "UTF-8");
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// 如果UTF-8失败,尝试使用系统默认编码
|
||||
return new String(Files.readAllBytes(filePath));
|
||||
} catch (Exception e2) {
|
||||
return "文件读取失败: " + e2.getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取目录统计信息
|
||||
* GET /api/file/stats
|
||||
*/
|
||||
@GetMapping("/stats")
|
||||
@ResponseBody
|
||||
public ResponseEntity<ApiResponseVo<Map<String, Object>>> getDirectoryStats() {
|
||||
try {
|
||||
Path directory = Paths.get(DIRECTORY_PATH);
|
||||
|
||||
if (!Files.exists(directory)) {
|
||||
return ResponseEntity.ok(new ApiResponseVo<>(false, "目录不存在: " + DIRECTORY_PATH, null));
|
||||
}
|
||||
|
||||
Map<String, Object> stats = new HashMap<>();
|
||||
int fileCount = 0;
|
||||
long totalSize = 0;
|
||||
List<String> fileNames = new ArrayList<>();
|
||||
|
||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
|
||||
for (Path file : stream) {
|
||||
if (Files.isRegularFile(file)) {
|
||||
fileCount++;
|
||||
totalSize += Files.size(file);
|
||||
fileNames.add(file.getFileName().toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats.put("directoryPath", DIRECTORY_PATH);
|
||||
stats.put("fileCount", fileCount);
|
||||
stats.put("totalSize", totalSize);
|
||||
stats.put("totalSizeMB", String.format("%.2f MB", totalSize / (1024.0 * 1024.0)));
|
||||
stats.put("fileNames", fileNames);
|
||||
stats.put("lastUpdated", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
|
||||
String message = String.format("目录统计: %d 个文件, 总大小 %.2f MB", fileCount, totalSize / (1024.0 * 1024.0));
|
||||
return ResponseEntity.ok(new ApiResponseVo<>(true, message, stats));
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMsg = "获取目录统计失败: " + e.getMessage();
|
||||
System.err.println(errorMsg);
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new ApiResponseVo<>(false, errorMsg, null));
|
||||
}
|
||||
}
|
||||
}
|
||||
27
klp-wms/src/main/java/com/klp/domain/FileInfo.java
Normal file
27
klp-wms/src/main/java/com/klp/domain/FileInfo.java
Normal file
@@ -0,0 +1,27 @@
|
||||
package com.klp.domain;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 文件信息实体类
|
||||
*/
|
||||
@Data
|
||||
public class FileInfo {
|
||||
private String fileName;
|
||||
private String fileContent;
|
||||
private long fileSize;
|
||||
private String lastModified;
|
||||
private String filePath;
|
||||
|
||||
public FileInfo() {
|
||||
}
|
||||
|
||||
public FileInfo(String fileName, String fileContent, long fileSize, String lastModified, String filePath) {
|
||||
this.fileName = fileName;
|
||||
this.fileContent = fileContent;
|
||||
this.fileSize = fileSize;
|
||||
this.lastModified = lastModified;
|
||||
this.filePath = filePath;
|
||||
}
|
||||
|
||||
}
|
||||
26
klp-wms/src/main/java/com/klp/domain/vo/ApiResponseVo.java
Normal file
26
klp-wms/src/main/java/com/klp/domain/vo/ApiResponseVo.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.klp.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 响应结果实体类
|
||||
*/
|
||||
@Data
|
||||
public class ApiResponseVo<T> {
|
||||
private boolean success;
|
||||
private String message;
|
||||
private T data;
|
||||
private long timestamp;
|
||||
|
||||
public ApiResponseVo() {
|
||||
this.timestamp = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public ApiResponseVo(boolean success, String message, T data) {
|
||||
this.success = success;
|
||||
this.message = message;
|
||||
this.data = data;
|
||||
this.timestamp = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
}
|
||||
5
testDirectory/1.txt
Normal file
5
testDirectory/1.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
这是一个测试文件能否读取到这个文件的内容并打印输出
|
||||
|
||||
|
||||
|
||||
|
||||
293
testDirectory/2.txt
Normal file
293
testDirectory/2.txt
Normal file
@@ -0,0 +1,293 @@
|
||||
|
||||
/**
|
||||
* 获取目录下所有文件信息
|
||||
* GET /api/file/list
|
||||
*/
|
||||
@GetMapping("/list")
|
||||
@ResponseBody
|
||||
public ResponseEntity<ApiResponse<List<FileInfo>>> getAllFiles() {
|
||||
try {
|
||||
Path directory = Paths.get(DIRECTORY_PATH);
|
||||
|
||||
// 检查目录是否存在
|
||||
if (!Files.exists(directory)) {
|
||||
return ResponseEntity.ok(new ApiResponse<>(false, "目录不存在: " + DIRECTORY_PATH, null));
|
||||
}
|
||||
|
||||
// 获取所有文件
|
||||
List<FileInfo> fileList = new ArrayList<>();
|
||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
|
||||
for (Path file : stream) {
|
||||
if (Files.isRegularFile(file)) {
|
||||
FileInfo fileInfo = readFileInfo(file);
|
||||
fileList.add(fileInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String message = String.format("成功获取 %d 个文件", fileList.size());
|
||||
return ResponseEntity.ok(new ApiResponse<>(true, message, fileList));
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMsg = "获取文件列表失败: " + e.getMessage();
|
||||
System.err.println(errorMsg);
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new ApiResponse<>(false, errorMsg, null));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件名删除文件
|
||||
* DELETE /api/file/delete/{fileName}
|
||||
*/
|
||||
@DeleteMapping("/delete/{fileName}")
|
||||
@ResponseBody
|
||||
public ResponseEntity<ApiResponse<String>> deleteFile(@PathVariable String fileName) {
|
||||
try {
|
||||
Path filePath = Paths.get(DIRECTORY_PATH, fileName);
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!Files.exists(filePath)) {
|
||||
return ResponseEntity.ok(new ApiResponse<>(false, "文件不存在: " + fileName, null));
|
||||
}
|
||||
|
||||
// 检查是否为普通文件
|
||||
if (!Files.isRegularFile(filePath)) {
|
||||
return ResponseEntity.ok(new ApiResponse<>(false, "不是普通文件: " + fileName, null));
|
||||
}
|
||||
|
||||
// 删除文件
|
||||
Files.delete(filePath);
|
||||
|
||||
String message = "文件删除成功: " + fileName;
|
||||
return ResponseEntity.ok(new ApiResponse<>(true, message, fileName));
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMsg = "删除文件失败: " + e.getMessage();
|
||||
System.err.println(errorMsg);
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new ApiResponse<>(false, errorMsg, null));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除文件
|
||||
* POST /api/file/batch-delete
|
||||
*/
|
||||
@PostMapping("/batch-delete")
|
||||
@ResponseBody
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> batchDeleteFiles(@RequestBody List<String> fileNames) {
|
||||
try {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
List<String> successList = new ArrayList<>();
|
||||
List<String> failedList = new ArrayList<>();
|
||||
|
||||
for (String fileName : fileNames) {
|
||||
try {
|
||||
Path filePath = Paths.get(DIRECTORY_PATH, fileName);
|
||||
|
||||
if (Files.exists(filePath) && Files.isRegularFile(filePath)) {
|
||||
Files.delete(filePath);
|
||||
successList.add(fileName);
|
||||
} else {
|
||||
failedList.add(fileName + " (文件不存在)");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
failedList.add(fileName + " (" + e.getMessage() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
result.put("successCount", successList.size());
|
||||
result.put("failedCount", failedList.size());
|
||||
result.put("successFiles", successList);
|
||||
result.put("failedFiles", failedList);
|
||||
|
||||
String message = String.format("批量删除完成: 成功 %d 个, 失败 %d 个",
|
||||
successList.size(), failedList.size());
|
||||
|
||||
return ResponseEntity.ok(new ApiResponse<>(true, message, result));
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMsg = "批量删除失败: " + e.getMessage();
|
||||
System.err.println(errorMsg);
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new ApiResponse<>(false, errorMsg, null));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动执行定时删除(删除3个月前的文件)
|
||||
* POST /api/file/cleanup
|
||||
*/
|
||||
@PostMapping("/cleanup")
|
||||
@ResponseBody
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> manualCleanup() {
|
||||
return performCleanup();
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时删除任务 - 每3个月执行一次
|
||||
* 删除3个月前的文件
|
||||
*/
|
||||
@Scheduled(cron = "0 0 2 1 */3 *") // 每3个月的第1天凌晨2点执行
|
||||
public void scheduledCleanup() {
|
||||
System.out.println("=== 开始执行定时删除任务 ===");
|
||||
System.out.println("执行时间: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
|
||||
ResponseEntity<ApiResponse<Map<String, Object>>> response = performCleanup();
|
||||
ApiResponse<Map<String, Object>> result = response.getBody();
|
||||
|
||||
if (result != null) {
|
||||
System.out.println("定时删除结果: " + result.getMessage());
|
||||
if (result.getData() != null) {
|
||||
Map<String, Object> data = result.getData();
|
||||
System.out.println("删除文件数量: " + data.get("deletedCount"));
|
||||
System.out.println("删除的文件: " + data.get("deletedFiles"));
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("=== 定时删除任务完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行清理操作
|
||||
*/
|
||||
private ResponseEntity<ApiResponse<Map<String, Object>>> performCleanup() {
|
||||
try {
|
||||
Path directory = Paths.get(DIRECTORY_PATH);
|
||||
|
||||
if (!Files.exists(directory)) {
|
||||
return ResponseEntity.ok(new ApiResponse<>(false, "目录不存在: " + DIRECTORY_PATH, null));
|
||||
}
|
||||
|
||||
// 计算3个月前的日期
|
||||
LocalDateTime threeMonthsAgo = LocalDateTime.now().minusMonths(3);
|
||||
|
||||
List<String> deletedFiles = new ArrayList<>();
|
||||
int deletedCount = 0;
|
||||
|
||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
|
||||
for (Path file : stream) {
|
||||
if (Files.isRegularFile(file)) {
|
||||
try {
|
||||
// 获取文件最后修改时间
|
||||
LocalDateTime fileModifiedTime = LocalDateTime.ofInstant(
|
||||
Files.getLastModifiedTime(file).toInstant(),
|
||||
java.time.ZoneId.systemDefault()
|
||||
);
|
||||
|
||||
// 如果文件修改时间早于3个月前,则删除
|
||||
if (fileModifiedTime.isBefore(threeMonthsAgo)) {
|
||||
Files.delete(file);
|
||||
deletedFiles.add(file.getFileName().toString());
|
||||
deletedCount++;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("删除文件失败: " + file.getFileName() + " - " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("deletedCount", deletedCount);
|
||||
result.put("deletedFiles", deletedFiles);
|
||||
result.put("cleanupTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
result.put("thresholdTime", threeMonthsAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
|
||||
String message = String.format("清理完成: 删除了 %d 个3个月前的文件", deletedCount);
|
||||
return ResponseEntity.ok(new ApiResponse<>(true, message, result));
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMsg = "清理操作失败: " + e.getMessage();
|
||||
System.err.println(errorMsg);
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new ApiResponse<>(false, errorMsg, null));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件信息
|
||||
*/
|
||||
private FileInfo readFileInfo(Path filePath) throws IOException {
|
||||
String fileName = filePath.getFileName().toString();
|
||||
String fileContent = readFileContent(filePath);
|
||||
long fileSize = Files.size(filePath);
|
||||
|
||||
LocalDateTime lastModified = LocalDateTime.ofInstant(
|
||||
Files.getLastModifiedTime(filePath).toInstant(),
|
||||
java.time.ZoneId.systemDefault()
|
||||
);
|
||||
String lastModifiedStr = lastModified.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||
|
||||
return new FileInfo(fileName, fileContent, fileSize, lastModifiedStr, filePath.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件内容
|
||||
*/
|
||||
private String readFileContent(Path filePath) throws IOException {
|
||||
try {
|
||||
// 尝试使用UTF-8编码读取
|
||||
return new String(Files.readAllBytes(filePath), "UTF-8");
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// 如果UTF-8失败,尝试使用系统默认编码
|
||||
return new String(Files.readAllBytes(filePath));
|
||||
} catch (Exception e2) {
|
||||
return "文件读取失败: " + e2.getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取目录统计信息
|
||||
* GET /api/file/stats
|
||||
*/
|
||||
@GetMapping("/stats")
|
||||
@ResponseBody
|
||||
public ResponseEntity<ApiResponse<Map<String, Object>>> getDirectoryStats() {
|
||||
try {
|
||||
Path directory = Paths.get(DIRECTORY_PATH);
|
||||
|
||||
if (!Files.exists(directory)) {
|
||||
return ResponseEntity.ok(new ApiResponse<>(false, "目录不存在: " + DIRECTORY_PATH, null));
|
||||
}
|
||||
|
||||
Map<String, Object> stats = new HashMap<>();
|
||||
int fileCount = 0;
|
||||
long totalSize = 0;
|
||||
List<String> fileNames = new ArrayList<>();
|
||||
|
||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
|
||||
for (Path file : stream) {
|
||||
if (Files.isRegularFile(file)) {
|
||||
fileCount++;
|
||||
totalSize += Files.size(file);
|
||||
fileNames.add(file.getFileName().toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats.put("directoryPath", DIRECTORY_PATH);
|
||||
stats.put("fileCount", fileCount);
|
||||
stats.put("totalSize", totalSize);
|
||||
stats.put("totalSizeMB", String.format("%.2f MB", totalSize / (1024.0 * 1024.0)));
|
||||
stats.put("fileNames", fileNames);
|
||||
stats.put("lastUpdated", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
|
||||
String message = String.format("目录统计: %d 个文件, 总大小 %.2f MB", fileCount, totalSize / (1024.0 * 1024.0));
|
||||
return ResponseEntity.ok(new ApiResponse<>(true, message, stats));
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMsg = "获取目录统计失败: " + e.getMessage();
|
||||
System.err.println(errorMsg);
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new ApiResponse<>(false, errorMsg, null));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user