Created
January 31, 2017 08:31
-
-
Save kntmr/8b7da9e8c9fcac7f20d32ff3b9f70e0d to your computer and use it in GitHub Desktop.
java.util.zip.ZipOutputStream による ZIP アーカイブ 2
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
package sample; | |
import java.io.BufferedInputStream; | |
import java.io.BufferedOutputStream; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.util.Collection; | |
import java.util.zip.ZipEntry; | |
import java.util.zip.ZipOutputStream; | |
import org.apache.commons.io.FileUtils; | |
public class ZipArchive2 { | |
void archive(String dirPath) { | |
ZipOutputStream zos = null; | |
try { | |
zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(dirPath + ".zip"))); | |
Collection<File> files = FileUtils.listFiles(new File(dirPath), null, true); | |
for (File file : files) { | |
String entryPath = file.getAbsolutePath().substring(dirPath.length() + 1); | |
ZipEntry entry = new ZipEntry(entryPath); | |
writeZipEntry(zos, file, entry); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} finally { | |
if (zos != null) { | |
try { | |
zos.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
void writeZipEntry(ZipOutputStream zos, File file, ZipEntry entry) throws IOException { | |
InputStream is = null; | |
byte[] buf = new byte[1024]; | |
try { | |
zos.putNextEntry(entry); | |
is = new BufferedInputStream(new FileInputStream(file)); | |
int len = 0; | |
while ((len = is.read(buf)) != -1) { | |
zos.write(buf, 0, len); | |
} | |
} finally { | |
if (is != null) { | |
try { | |
is.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment