|
@@ -9,6 +9,8 @@ import java.nio.channels.FileChannel;
|
|
|
import java.nio.file.*;
|
|
|
import java.text.DecimalFormat;
|
|
|
import java.util.Objects;
|
|
|
+import java.util.zip.ZipEntry;
|
|
|
+import java.util.zip.ZipOutputStream;
|
|
|
|
|
|
@Component
|
|
|
public class FileManager {
|
|
@@ -421,4 +423,78 @@ public class FileManager {
|
|
|
}
|
|
|
return result;
|
|
|
}
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 压缩文件夹
|
|
|
+ */
|
|
|
+ public boolean createZipFile(String tempZipFilePath, String folderToCompress ) {
|
|
|
+ boolean result = true;
|
|
|
+ if ( !isFolderExists(folderToCompress)) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ if (isFolderExists( tempZipFilePath )) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ FileOutputStream fileOutputStream = null;
|
|
|
+ ZipOutputStream zipOutputStream = null;
|
|
|
+ try {
|
|
|
+ fileOutputStream = new FileOutputStream(tempZipFilePath);
|
|
|
+ zipOutputStream = new ZipOutputStream(fileOutputStream);
|
|
|
+ compressFolder(folderToCompress, zipOutputStream);
|
|
|
+ } catch (IOException e) {
|
|
|
+ result = false;
|
|
|
+ } finally {
|
|
|
+ try {
|
|
|
+ if ( Objects.nonNull(fileOutputStream) ) {
|
|
|
+ fileOutputStream.close();
|
|
|
+ }
|
|
|
+ if ( Objects.nonNull(zipOutputStream)) {
|
|
|
+ zipOutputStream.close();
|
|
|
+ }
|
|
|
+ } catch (Exception ignored) {}
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ private void compressFolder(String sourceFolder, ZipOutputStream zipOutputStream) {
|
|
|
+ File folder = new File(sourceFolder);
|
|
|
+ File[] files = folder.listFiles();
|
|
|
+ if (files != null) {
|
|
|
+ for (File file : files) {
|
|
|
+ if (file.isDirectory()) {
|
|
|
+ compressFolder( sourceFolder + separator + file.getName(), zipOutputStream);
|
|
|
+ } else {
|
|
|
+ addToZipFile(file.getName(), sourceFolder + File.separator + file.getName(), zipOutputStream);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void addToZipFile(String fileName, String fileAbsolutePath, ZipOutputStream zipOutputStream) {
|
|
|
+ FileInputStream fileInputStream = null;
|
|
|
+ ZipEntry entry = new ZipEntry(fileName);
|
|
|
+ try {
|
|
|
+ zipOutputStream.putNextEntry(entry);
|
|
|
+ fileInputStream = new FileInputStream(fileAbsolutePath);
|
|
|
+ byte[] buffer = new byte[1024];
|
|
|
+ int bytesRead;
|
|
|
+ while ((bytesRead = fileInputStream.read(buffer)) != -1) {
|
|
|
+ zipOutputStream.write(buffer, 0, bytesRead);
|
|
|
+ }
|
|
|
+ } catch (Exception ignored) {}finally {
|
|
|
+ try {
|
|
|
+ if ( Objects.nonNull(zipOutputStream )) {
|
|
|
+ zipOutputStream.closeEntry();
|
|
|
+ }
|
|
|
+ if ( Objects.nonNull(fileInputStream)) {
|
|
|
+ fileInputStream.close();
|
|
|
+ }
|
|
|
+ } catch (IOException ignored) {}
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String getFileFullName(String fileAbsolutePath) {
|
|
|
+ String[] names = fileAbsolutePath.replace("\\", "/").split("/");
|
|
|
+ return names[names.length -1];
|
|
|
+ }
|
|
|
}
|