zip unzip
压缩是编写文件时可以在我们的代码中发出的主要动作之一。 因此,我发现在zip和unzip上必不可少的简单Java代码段,并且必须易于访问。
要点是纯Java语言,并以zip格式存储两个文件。 完成后,打开打开的拉链并评估其内容。
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;import java.io.*;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;/*** Created by gkatzioura on 4/12/17.*/
public class ArhivingTest {private static final String TEXT_ENTRY_1 = "text1.txt";private static final String TEXT_ENTRY_2 = "text2.txt";@Testpublic void zipAndUnzip() throws IOException {String text1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ";String text2 = "eiusmod tempor incididunt ut labore et dolore magna aliqua. ";File tempZip = File.createTempFile("temp",".zip");try(OutputStream outputStream = new FileOutputStream(tempZip);ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {zipOutputStream.putNextEntry(new ZipEntry(TEXT_ENTRY_1));zipOutputStream.write(text1.getBytes());zipOutputStream.closeEntry();zipOutputStream.putNextEntry(new ZipEntry(TEXT_ENTRY_2));zipOutputStream.write(text2.getBytes());zipOutputStream.closeEntry();}try(InputStream inputStream = new FileInputStream(tempZip);ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {ZipEntry entry = null;while ((entry=zipInputStream.getNextEntry())!=null) {if(entry.getName().equals(TEXT_ENTRY_1)) {Assert.assertEquals(text1, IOUtils.toString(zipInputStream));}if(entry.getName().equals(TEXT_ENTRY_2)) {Assert.assertEquals(text2,IOUtils.toString(zipInputStream));}zipInputStream.closeEntry();}} finally {Files.deleteIfExists(tempZip.toPath());}}}
翻译自: https://www.javacodegeeks.com/2017/04/java-gist-zip-unzip.html
zip unzip