|
@@ -0,0 +1,103 @@
|
|
|
+package com.qmth.boot.tools.io;
|
|
|
+
|
|
|
+import com.sun.istack.internal.NotNull;
|
|
|
+import com.sun.istack.internal.Nullable;
|
|
|
+import org.apache.commons.lang3.ArrayUtils;
|
|
|
+import org.apache.commons.lang3.StringUtils;
|
|
|
+
|
|
|
+import java.io.*;
|
|
|
+import java.util.zip.ZipEntry;
|
|
|
+import java.util.zip.ZipOutputStream;
|
|
|
+
|
|
|
+/**
|
|
|
+ * ZIP格式写入工具
|
|
|
+ */
|
|
|
+public class ZipWriter {
|
|
|
+
|
|
|
+ private ZipOutputStream ous;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 创建输出到通用输出流的ZIP内容
|
|
|
+ *
|
|
|
+ * @param outputStream
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public static ZipWriter create(OutputStream outputStream) {
|
|
|
+ return new ZipWriter(outputStream);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 创建输出到本地文件的ZIP内容
|
|
|
+ *
|
|
|
+ * @param file
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public static ZipWriter create(File file) throws FileNotFoundException {
|
|
|
+ return create(new FileOutputStream(file));
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 创建输出到byte[]的ZIP内容
|
|
|
+ *
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public static ZipWriter create() {
|
|
|
+ return create(new ByteArrayOutputStream());
|
|
|
+ }
|
|
|
+
|
|
|
+ private ZipWriter(OutputStream outputStream) {
|
|
|
+ this.ous = new ZipOutputStream(outputStream);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 使用通用数据流增加ZIP内部文件,path包括完整的内部路径,至少包含内部文件名
|
|
|
+ *
|
|
|
+ * @param inputStream
|
|
|
+ * @param path
|
|
|
+ * @throws IOException
|
|
|
+ */
|
|
|
+ public void write(@NotNull InputStream inputStream, @NotNull String... path) throws IOException {
|
|
|
+ if (path == null || path.length == 0) {
|
|
|
+ throw new RuntimeException("path should not be empty");
|
|
|
+ }
|
|
|
+ ous.putNextEntry(new ZipEntry(StringUtils.join(path, File.separator)));
|
|
|
+ IOUtils.copy(inputStream, ous);
|
|
|
+ IOUtils.closeQuietly(inputStream);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 使用本地文件增加ZIP内部文件,dir表示完整的内部路径,可以为空;不指定内部文件名时,直接使用本地文件名
|
|
|
+ *
|
|
|
+ * @param file
|
|
|
+ * @param name
|
|
|
+ * @param dir
|
|
|
+ * @throws IOException
|
|
|
+ */
|
|
|
+ public void write(@NotNull File file, @Nullable String name, @Nullable String... dir) throws IOException {
|
|
|
+ if (name == null) {
|
|
|
+ name = file.getName();
|
|
|
+ }
|
|
|
+ if (dir == null || dir.length == 0) {
|
|
|
+ dir = new String[] { name };
|
|
|
+ } else {
|
|
|
+ dir = ArrayUtils.add(dir, name);
|
|
|
+ }
|
|
|
+ write(new FileInputStream(file), dir);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 使用byte[]增加ZIP内部文件,path包括完整的内部路径,至少包含内部文件名
|
|
|
+ *
|
|
|
+ * @param data
|
|
|
+ * @param path
|
|
|
+ * @throws IOException
|
|
|
+ */
|
|
|
+ public void write(@NotNull byte[] data, @NotNull String... path) throws IOException {
|
|
|
+ write(new ByteArrayInputStream(data), path);
|
|
|
+ }
|
|
|
+
|
|
|
+ public void close() {
|
|
|
+ IOUtils.closeQuietly(ous);
|
|
|
+ }
|
|
|
+
|
|
|
+}
|