示例
@RestController
public class FileController {private static final Logger logger = LoggerFactory.getLogger(FileController.class);private static final String filePath = "/fileTemp";@Autowiredprivate ObjectMapper objectMapper;@GetMapping("/v1/file/add")public void add() {}@GetMapping("/v1/file/zip")public ResponseEntity<byte[]> zip() {File tempJSONFile, tempPngFile;String outputFileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));try {File tempFileDirectory = new File(filePath);if (!tempFileDirectory.exists()) {boolean dirCreateFlag = tempFileDirectory.mkdirs();logger.info("临时文件目录创建成功: {}", dirCreateFlag);}Map<String, String> data = new HashMap<>();data.put("1", "1");for (int i = 0; i < 10; i++) {tempJSONFile = createJsonFile(i, "deviceId_" + i + ".json", objectMapper.writeValueAsString(data));if (tempJSONFile.exists()) {logger.info("JSON文件已创建");} else {logger.info("JSON文件未创建");}ImageTool.downloadImage("http://app.test.stesh.cn/images/zjlogo.png", filePath + "/" + i ,"deviceId_" + i + ".png");}ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipTool.createZipFile(tempFileDirectory, baos);deleteDirectory(tempFileDirectory);HttpHeaders headers = new HttpHeaders();headers.add("Content-Disposition", "attachment; filename=" + outputFileName + ".zip");return ResponseEntity.ok().headers(headers).contentLength(baos.size()).body(baos.toByteArray());} catch (IOException e) {e.printStackTrace();logger.info("error: {}", e.getMessage());} finally {}return null;}public void zipDirectory(File directory, ZipOutputStream zos) throws IOException {zipFiles(directory, "", zos);zos.close();}private void zipFiles(File directory, String baseName, ZipOutputStream zos) throws IOException {File[] files = directory.listFiles();byte[] buffer = new byte[1024];int length;for (File file : files) {if (file.isDirectory()) {logger.info("baseName:{}", baseName);String subDirName = (baseName.isEmpty() ? "" : baseName + "/") + file.getName();zipFiles(file, subDirName, zos);continue;}ZipEntry zipEntry = new ZipEntry(baseName.isEmpty() ? file.getName() : baseName + "/" + file.getName());zos.putNextEntry(zipEntry);try (FileInputStream fis = new FileInputStream(file)) {while ((length = fis.read(buffer)) > 0) {zos.write(buffer, 0, length);}}zos.closeEntry();}}public File createJsonFile(Integer i, String fileName, String jsonString) throws IOException {File tempFileDirectory = new File(filePath + "/" + i);if (!tempFileDirectory.exists()) {boolean dirCreateFlag = tempFileDirectory.mkdirs();logger.info("临时文件目录创建成功: {}", dirCreateFlag);}File jsonFile = new File(filePath + "/" + i + "/" + fileName);try (FileWriter fileWriter = new FileWriter(jsonFile)) {fileWriter.write(jsonString);} catch (IOException e) {e.printStackTrace();}return jsonFile;}public static void deleteDirectory(File directory) {if (directory.exists()) {File[] files = directory.listFiles();if (files != null) {for (File file : files) {if (file.isDirectory()) {deleteDirectory(file);} else {file.delete();}}}directory.delete();}}private String get(String url, Map<String, String> headers, Map<String, String> querys) {HttpClient httpClient = null;HttpGet httpGet = null;String result = null;try {httpClient = new SSLClient();URIBuilder builder = new URIBuilder(url);if (!CollectionUtils.isEmpty(querys)) {for (String key : querys.keySet()) {builder.setParameter(key, String.valueOf(querys.get(key)));}}httpGet = new HttpGet(builder.build());if (!CollectionUtils.isEmpty(headers)) {for (String headerName : headers.keySet()) {httpGet.addHeader(headerName, headers.get(headerName));}}RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(1000).setSocketTimeout(10000).build();httpGet.setConfig(requestConfig);HttpResponse response = httpClient.execute(httpGet);if (response != null) {HttpEntity resEntity = response.getEntity();if (resEntity != null) {result = EntityUtils.toString(resEntity, "UTF-8");}}} catch (Exception ex) {ex.printStackTrace();}return result;}
}
http下载图片并写入文件
public class ImageTool {public static void downloadImage(String imageUrl, String saveFilePath, String fileName) {CloseableHttpClient httpClient = HttpClients.createDefault();HttpGet httpGet = new HttpGet(imageUrl);try {CloseableHttpResponse response = httpClient.execute(httpGet);File tempFileDirectory = new File(saveFilePath);System.out.println("path:" + tempFileDirectory.getAbsolutePath());if (!tempFileDirectory.exists()) {boolean dirCreateFlag = tempFileDirectory.mkdirs();}FileOutputStream fos = new FileOutputStream(saveFilePath + "/" + fileName);HttpEntity entity = response.getEntity();if (entity != null) {entity.writeTo(fos);System.out.println("Image downloaded successfully!");}} catch (IOException e) {e.printStackTrace();} finally {try {if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}}
}
将文件压缩为zip文件
public class ZipTool {public static void zipFiles(File directory, String baseName, ZipArchiveOutputStream zos) throws IOException {File[] files = directory.listFiles();if (files == null) {return; }for (File file : files) {Path filePath = file.toPath();String entryName = baseName.isEmpty() ? filePath.getFileName().toString() : baseName + "/" + filePath.getFileName().toString();if (Files.isDirectory(filePath)) {ZipArchiveEntry dirEntry = new ZipArchiveEntry(entryName + "/"); zos.putArchiveEntry(dirEntry);zos.closeArchiveEntry();zipFiles(file, entryName, zos);continue;}ZipArchiveEntry fileEntry = new ZipArchiveEntry(entryName);zos.putArchiveEntry(fileEntry);try (InputStream fis = Files.newInputStream(filePath)) {byte[] buffer = new byte[1024];int length;while ((length = fis.read(buffer)) > 0) {zos.write(buffer, 0, length);}}zos.closeArchiveEntry();}}public static void createZipFile(File directory, ByteArrayOutputStream byteArrayOutputStream) {ZipArchiveOutputStream zos = null;try {zos = new ZipArchiveOutputStream(byteArrayOutputStream);zipFiles(directory, "", zos);} catch (IOException e){e.printStackTrace();} finally {try {if (zos != null) {zos.close();}} catch (IOException e) {e.printStackTrace();}}}
}