Created
August 25, 2016 20:45
-
-
Save shinshin86/7ed07c7981e258be72bf312aa711bd6b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedInputStream; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.zip.ZipEntry; | |
import java.util.zip.ZipOutputStream; | |
public class CreateZip { | |
static byte[] buf = new byte[1024]; | |
/** | |
* Create ZIP | |
* | |
* @param inputPath | |
* ZIP compression target path | |
* @param outputZip | |
* Create ZIP File path | |
* @throws IOException | |
*/ | |
public static void createZip(String inputPath, String outputZip) throws IOException { | |
// Specify the compression target with a relative path | |
File[] inputFiles = { new File(inputPath) }; | |
// Create ZIP File name | |
File outputFile = new File(outputZip); | |
// Output stream filter for writing files in the ZIP file format. | |
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outputFile)); | |
// Compression target root path | |
Path root = Paths.get(inputFiles[0].getParent()); | |
try { | |
// ZIP compression | |
encode(inputFiles, zos, root); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} finally { | |
zos.close(); | |
} | |
} | |
/** | |
* @param inputFiles | |
* ZIP target files | |
* @param zos | |
* Output stream (ZIP) | |
* @param root | |
* Compression target root path | |
* @throws Exception | |
*/ | |
static void encode(File[] inputFiles, ZipOutputStream zos, Path root) throws Exception { | |
for (File f : inputFiles) { | |
if (f.isDirectory()) { | |
// To recursively processing | |
encode(f.listFiles(), zos, root); | |
} else { | |
Path p = Paths.get(f.getAbsolutePath()); | |
// In the case of Windows, to replace | |
ZipEntry entry = new ZipEntry( | |
(p.subpath(root.getNameCount(), p.getNameCount())).toString().replace('\\', '/')); | |
zos.putNextEntry(entry); | |
try (InputStream is = new BufferedInputStream(new FileInputStream(f))) { | |
for (;;) { | |
int len = is.read(buf); | |
if (len < 0) | |
break; | |
zos.write(buf, 0, len); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment