Java 文件上传,下载,复制,删除,Zip文件解压缩,文件内容修改,JSON 文件中字段值的修改,递归删除文件夹及其子文件等
Controller
import org. springframework. core. io. Resource ;
import org. springframework. http. ResponseEntity ; @Slf4j
@RestController
@AllArgsConstructor
@Api ( tags = "文件相关操作接口" )
@RequestMapping ( "/file" )
public class FileController
{ @ApiOperation ( value = "文件批量上传" ) @PostMapping ( "/uploadFiles" ) public Result < ? > uploadFiles ( @RequestParam ( value = "file" ) MultipartFile [ ] files, String tempFilePath) { List < Map < String , Object > > list; try { list = FileUtil . uploadFiles ( files, tempFilePath) ; } catch ( Exception e) { return Result . fail ( e. getMessage ( ) ) ; } return Result . success ( list) ; } @PostMapping ( "/deleteFiles" ) @ApiOperation ( "批量删除文件" ) public void deleteFiles ( @RequestParam ( value = "files" ) String [ ] fileNames, String targetPath) { FileUtil . deleteFiles ( fileNames, targetPath) ; } @ApiOperation ( "文件下载" ) @GetMapping ( "/download" ) public ResponseEntity < Resource > download ( @RequestParam String filePath, String fileName) { try { return FileUtil . download ( filePath, fileName) ; } catch ( Exception e) { log. error ( "文件下载失败" , e) ; throw new RuntimeException ( e) ; } } }
FileUtil
文件批量上传 批量删除文件 文件下载 压缩包校验 Zip文件解压缩 创建文件夹 递归地删除文件夹及其所有内容 复制文件夹中的所有内容 复制文件,将从源目录中的文件复制到目标目录中 修改 JSON 文件中指定字段的值 修改文件内容
@Slf4j
public class FileUtil
{ public static List < Map < String , Object > > uploadFiles ( MultipartFile [ ] files, String targetPath) { int size = 0 ; for ( MultipartFile file : files) { size = ( int ) file. getSize ( ) + size; } List < Map < String , Object > > fileInfoList = new ArrayList < > ( ) ; for ( int i = 0 ; i < files. length; i++ ) { Map < String , Object > map = new HashMap < > ( ) ; String fileName = files[ i] . getOriginalFilename ( ) ; String fileServiceName = UUID . randomUUID ( ) . toString ( ) . replace ( "-" , "" ) + "_" + fileName; File filePath = new File ( targetPath, fileServiceName) ; map. put ( "fileServiceName" , fileServiceName) ; map. put ( "fileName" , fileName) ; map. put ( "filePath" , filePath) ; if ( ! filePath. getParentFile ( ) . exists ( ) ) { filePath. getParentFile ( ) . mkdirs ( ) ; } try { files[ i] . transferTo ( filePath) ; } catch ( IOException e) { log. error ( "文件上传失败" , e) ; throw new CustomException ( "文件上传失败" ) ; } fileInfoList. add ( map) ; } return fileInfoList; } public static void deleteFiles ( String [ ] fileNames, String targetPath) { for ( String fileName : fileNames) { String filePath = targetPath + fileName; File file = new File ( filePath) ; if ( file. exists ( ) ) { try { Files . delete ( file. toPath ( ) ) ; } catch ( IOException e) { e. printStackTrace ( ) ; log. warn ( "文件删除失败" , e) ; } } else { log. warn ( "文件: {} 删除失败,该文件不存在" , fileName) ; } } } public static ResponseEntity < Resource > download ( String filePath, String fileName) throws MalformedURLException , UnsupportedEncodingException { Resource resource = loadFileAsResource ( filePath, fileName) ; String encodedFileName = URLEncoder . encode ( Objects . requireNonNull ( resource. getFilename ( ) ) , "UTF-8" ) . replaceAll ( "\\+" , "%20" ) ; return ResponseEntity . ok ( ) . contentType ( MediaType . parseMediaType ( ContentType . OCTET_STREAM . getValue ( ) ) ) . header ( HttpHeaders . CONTENT_DISPOSITION , "attachment; filename=" + encodedFileName) . body ( resource) ; } private static Resource loadFileAsResource ( String filePath, String fileName) throws MalformedURLException { Path path; if ( StringUtils . isEmpty ( fileName) ) { path = Paths . get ( filePath) ; } else { path = Paths . get ( filePath + File . separator + fileName) ; } Resource resource = new UrlResource ( path. toUri ( ) ) ; if ( resource. exists ( ) || resource. isReadable ( ) ) { return resource; } else { throw new RuntimeException ( "找不到文件或无法读取文件" ) ; } } public static void zipVerify ( String zipFilePath, String suffix) throws Exception { try ( ZipInputStream zipInputStream = new ZipInputStream ( Files . newInputStream ( Paths . get ( zipFilePath) ) ) ) { ZipEntry entry = zipInputStream. getNextEntry ( ) ; boolean allFilesAreSameSuffix = true ; while ( entry != null ) { String entryName = entry. getName ( ) ; if ( ! entryName. toLowerCase ( ) . endsWith ( suffix) ) { allFilesAreSameSuffix = false ; break ; } zipInputStream. closeEntry ( ) ; entry = zipInputStream. getNextEntry ( ) ; } if ( ! allFilesAreSameSuffix) { throw new RuntimeException ( "压缩包中存在非" + suffix + "文件,校验失败" ) ; } } } public static List < String > unzip ( String zipFilePath, String destDirectory) throws Exception { List < String > fileNameList = new ArrayList < > ( ) ; File destDir = new File ( destDirectory) ; if ( ! destDir. exists ( ) ) { destDir. mkdirs ( ) ; } try ( ZipInputStream zipInputStream = new ZipInputStream ( Files . newInputStream ( Paths . get ( zipFilePath) ) ) ) { ZipEntry entry = zipInputStream. getNextEntry ( ) ; byte [ ] buffer = new byte [ 1024 ] ; while ( entry != null ) { String entryName = entry. getName ( ) ; File newFile = new File ( destDirectory + File . separator + entryName) ; try ( FileOutputStream fos = new FileOutputStream ( newFile) ) { int len; while ( ( len = zipInputStream. read ( buffer) ) > 0 ) { fos. write ( buffer, 0 , len) ; } } zipInputStream. closeEntry ( ) ; fileNameList. add ( entryName) ; entry = zipInputStream. getNextEntry ( ) ; } } log. info ( "解压缩并校验完成" ) ; return fileNameList; } public static void createFolder ( String folderPath) { File folder = new File ( folderPath) ; if ( ! folder. exists ( ) ) { if ( ! folder. mkdirs ( ) ) { throw new RuntimeException ( "文件夹创建失败: " + folderPath) ; } } } public static void deleteFolder ( String folderPath) { File folder = new File ( folderPath) ; if ( folder. exists ( ) ) { File [ ] files = folder. listFiles ( ) ; if ( files != null ) { for ( File file : files) { if ( file. isDirectory ( ) ) { deleteFolder ( file. getAbsolutePath ( ) ) ; } else { file. delete ( ) ; } } } folder. delete ( ) ; log. info ( "文件夹{}删除成功!" , folderPath) ; } } public static String copyFolderOfAll ( String sourceFolderPath, String targetFolderPath, String newFolderName) { String destinationFolderPath = targetFolderPath + File . separator + newFolderName; Path sourcePath = Paths . get ( sourceFolderPath) ; Path destinationPath = Paths . get ( destinationFolderPath) ; try { Files . walk ( sourcePath) . forEach ( source -> { try { Path destination = destinationPath. resolve ( sourcePath. relativize ( source) ) ; if ( Files . isDirectory ( source) ) { if ( ! Files . exists ( destination) ) { Files . createDirectory ( destination) ; } } else { Files . copy ( source, destination, StandardCopyOption . REPLACE_EXISTING ) ; } } catch ( IOException e) { throw new RuntimeException ( "复制文件夹失败: " + e. getMessage ( ) ) ; } } ) ; } catch ( Exception e) { log. error ( "文件夹复制失败: {}" , e) ; FileUtil . deleteFolder ( destinationFolderPath) ; throw new RuntimeException ( "文件夹复制失败" ) ; } return destinationFolderPath; } public static void copeFile ( String sourceFilePath, String destinationDirectory, String newFileName) { Path sourceFile = Paths . get ( sourceFilePath) ; Path destinationFile = Paths . get ( destinationDirectory, newFileName) ; try { Files . copy ( sourceFile, destinationFile) ; log. info ( "File copied successfully from " + sourceFile + " to " + destinationFile) ; } catch ( IOException e) { log. error ( "Error copying file: " + e. getMessage ( ) ) ; } } public static void modifyJsonField ( String filePath, String fieldName, Object newValue) { try { ObjectMapper objectMapper = new ObjectMapper ( ) ; File file = new File ( filePath) ; JsonNode jsonNode = objectMapper. readTree ( file) ; if ( jsonNode. isObject ( ) ) { ObjectNode objectNode = ( ObjectNode ) jsonNode; objectNode. putPOJO ( fieldName, newValue) ; objectMapper. writeValue ( file, objectNode) ; log. info ( "Field '" + fieldName + "' in the JSON file has been modified to: " + newValue) ; } else { log. info ( "Invalid JSON format in the file." ) ; } } catch ( IOException e) { throw new RuntimeException ( e) ; } } public static void modifyFileContent ( String filePath, String searchString, String replacement) { try { File file = new File ( filePath) ; BufferedReader reader = new BufferedReader ( new FileReader ( file) ) ; String line; StringBuilder content = new StringBuilder ( ) ; while ( ( line = reader. readLine ( ) ) != null ) { if ( line. contains ( searchString) ) { line = line. replace ( searchString, replacement) ; } content. append ( line) . append ( "\n" ) ; } reader. close ( ) ; BufferedWriter writer = new BufferedWriter ( new FileWriter ( file) ) ; writer. write ( content. toString ( ) ) ; writer. close ( ) ; log. info ( "文件内容[" + searchString + "]已被修改为[" + replacement + "]" ) ; } catch ( IOException e) { throw new RuntimeException ( e) ; } }
}