public void DeletePDF(String FilePath, String ZipFilePath) { try { // 创建一个ZIP输出流 FileOutputStream fos = new FileOutputStream(ZipFilePath); ZipOutputStream zipOut = new ZipOutputStream(fos); // 获取文件夹中的所有PDF文件 File folder = new File(FilePath);//FilePath(例:C:\Users\ANUB\Desktop) File[] files = folder.listFiles((dir, name) -> name.toLowerCase().endsWith(".pdf")); // 将每个PDF文件添加到ZIP压缩包中 if (files != null) { for (File file : files) { FileInputStream fis = new FileInputStream(file); // 在ZIP中创建一个新的条目 zipOut.putNextEntry(new ZipEntry(file.getName())); // 将文件内容写入ZIP条目 byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { zipOut.write(buffer, 0, length); } // 关闭当前条目并准备下一个条目 zipOut.closeEntry(); fis.close(); } // 关闭ZIP输出流 zipOut.close(); // 删除所有PDF文件 for (File file : files) { file.delete(); } } } catch (IOException e) { e.printStackTrace(); } }
Java删除指定文件夹下的文件并生成压缩包
最新推荐文章于 2024-01-22 00:35:20 发布