下面列出了java.util.zip.ZipOutputStream#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private byte[] createAlmostEmptyZipFile(final byte[] content) throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
final ZipOutputStream zos = new ZipOutputStream(bos);
zos.setMethod(ZipOutputStream.DEFLATED);
zos.setLevel(0);
for (final String name : Arrays
.asList(ManifestElement.META_INF_MANIFEST_XML, "mimetype", "Thumbnails",
"content.xml")) {
final ZipEntry e = new ZipEntry(name);
zos.putNextEntry(e);
zos.write(content);
}
zos.finish();
zos.close();
return bos.toByteArray();
}
public static void packZip(List<File> sources, File output) throws IOException {
EditorLogger.debug("Packaging to " + output.getName());
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(output));
zipOut.setLevel(Deflater.DEFAULT_COMPRESSION);
for (File source : sources) {
if (source.isDirectory()) {
zipDir(zipOut, "", source);
} else {
zipFile(zipOut, "", source);
}
}
zipOut.flush();
zipOut.close();
EditorLogger.debug("Done");
}
public static void main(final String[] args) throws IOException {
final String sourceFile = "src/main/resources/zipTest/test1.txt";
final FileOutputStream fos = new FileOutputStream("src/main/resources/compressed.zip");
final ZipOutputStream zipOut = new ZipOutputStream(fos);
final File fileToZip = new File(sourceFile);
final FileInputStream fis = new FileInputStream(fileToZip);
final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
zipOut.close();
fis.close();
fos.close();
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
public static boolean zipFile(String baseDirName, String fileName, String targerFileName) throws IOException {
if (baseDirName == null || "".equals(baseDirName)) {
return false;
}
File baseDir = new File(baseDirName);
if (!baseDir.exists() || !baseDir.isDirectory()) {
return false;
}
String baseDirPath = baseDir.getAbsolutePath();
File targerFile = new File(targerFileName);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(targerFile));
File file = new File(baseDir, fileName);
boolean zipResult = false;
if (file.isFile()) {
zipResult = fileToZip(baseDirPath, file, out);
} else {
zipResult = dirToZip(baseDirPath, file, out);
}
out.close();
return zipResult;
}
public static void zipFile(String filePath, String zipPath) throws Exception{
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipPath);
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze= new ZipEntry("spy.log");
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(filePath);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
//remember close it
zos.close();
}
private static File createZip(Map<String, String> files) throws Exception {
File f = Os.newTempFile("osgi", "zip");
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(f));
for (Map.Entry<String, String> entry : files.entrySet()) {
ZipEntry ze = new ZipEntry(entry.getKey());
zip.putNextEntry(ze);
zip.write(entry.getValue().getBytes());
}
zip.closeEntry();
zip.flush();
zip.close();
return f;
}
private static void writeJar(String jarFile, Manifest manifest, String classes[], int from, int to) throws Exception {
if (DEBUG) {
System.out.println("ClassFileInstaller: Writing to " + getJarPath(jarFile));
}
(new File(jarFile)).delete();
FileOutputStream fos = new FileOutputStream(jarFile);
ZipOutputStream zos = new ZipOutputStream(fos);
// The manifest must be the first or second entry. See comments in JarInputStream
// constructor and JDK-5046178.
if (manifest != null) {
writeToDisk(zos, "META-INF/MANIFEST.MF", manifest.getInputStream());
}
for (int i=from; i<to; i++) {
writeClassToDisk(zos, classes[i]);
}
zos.close();
fos.close();
}
private static void learn() throws IOException {
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(learnOptions.modelFile)));
if (learnOptions.trainReranker) {
new Reranker(learnOptions, zos);
} else {
BrownCluster bc = Learn.learnOptions.brownClusterFile == null ? null
: new BrownCluster(Learn.learnOptions.brownClusterFile);
WordEmbedding we = Learn.learnOptions.wordEmbeddingFile == null ? null
: new WordEmbedding(Learn.learnOptions.wordEmbeddingFile);
SentenceReader reader = new AllCoNLL09Reader(
learnOptions.inputCorpus);
Pipeline.trainNewPipeline(reader, learnOptions.getFeatureFiles(),
zos, bc, we);
}
zos.close();
}
@Override
public RR436Response findRR436(List<String> idCodes) throws XRoadServiceConsumptionException {
String base64 = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zipStream = new ZipOutputStream(outputStream);
ZipEntry entry = new ZipEntry("rr436_idcodes.txt");
try {
zipStream.putNextEntry(entry);
for (String isikukood : idCodes) {
zipStream.write(isikukood.getBytes("UTF-8"));
zipStream.write(System.getProperty("line.separator").getBytes("UTF-8"));
}
zipStream.closeEntry();
zipStream.close();
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = outputStream.toByteArray();
base64 = Base64.encodeBase64String(bytes);
RR436 paring = RR436.Factory.newInstance();
RR436RequestType request = paring.addNewRequest();
request.setIsikukoodideArv(String.valueOf(idCodes.size()));
request.setCFailiSisu(base64);
return rrV5XRoadDatabase.rr436V1(paring);
}
public static void zipDirectory(File dir, String zipTopLevelDir) throws Exception {
FileOutputStream zipFile = new FileOutputStream(new File(dir.getParent(), dir.getName() + ".zip"));
ZipOutputStream zipOutputStream = new ZipOutputStream(zipFile);
try {
addDirectory(zipOutputStream, zipTopLevelDir, dir, "");
} finally {
zipOutputStream.close();
}
}
private static FileObject createZipFile (
@NonNull final FileObject folder,
@NonNull final String name,
@NonNull final String path,
@NonNull final String content) throws IOException {
final FileObject zipRoot1 = folder.createData(name);
final FileLock lock = zipRoot1.lock();
try {
final ZipOutputStream zout = new ZipOutputStream(zipRoot1.getOutputStream(lock)); //NOI18N
try {
final String[] pathElements = path.split("/"); //NOI18N
final StringBuilder currentPath = new StringBuilder();
for (String element : pathElements) {
if (currentPath.length() > 0) {
currentPath.append('/'); //NOI18N
}
currentPath.append(element);
zout.putNextEntry(new ZipEntry(currentPath.toString()));
}
zout.write(content.getBytes(Charset.defaultCharset()));
} finally {
zout.close();
}
} finally {
lock.releaseLock();
}
return FileUtil.getArchiveRoot(zipRoot1);
}
public ByteArrayOutputStream export() {
try {
ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(byteArrayStream));
addToZipFile("site.json", export(site), zipOutputStream);
for (Page page : getSite().getPagesSet()) {
addToZipFile("pages/" + page.getSlug() + ".json", export(page), zipOutputStream);
}
for (Post post : getSite().getPostSet()) {
addToZipFile("posts/" + post.getSlug() + ".json", export(post), zipOutputStream);
}
for (Category category : getSite().getCategoriesSet()) {
addToZipFile("categories/" + category.getSlug() + ".json", export(category), zipOutputStream);
}
for (Menu menu : getSite().getMenusSet()) {
addToZipFile("menus/" + menu.getSlug() + ".json", export(menu), zipOutputStream);
}
for (GroupBasedFile file : getSite().getPostSet().stream()
.flatMap(post -> post.getFilesSet().stream()).map(PostFile::getFiles).distinct().collect(toList())) {
addToZipFile("files/" + file.getExternalId(), file.getStream(), zipOutputStream);
}
zipOutputStream.close();
return byteArrayStream;
} catch (IOException e) {
throw new RuntimeException("Error exporting site " + site.getSlug(), e);
}
}
/**
* Make an arbitrary zip archive in memory using the specified entries.
* @param entriesInFileOrder the entries
* @return the zip file described above, as a byte array
*/
public static byte[] makeTestZip(List<UnitTestZipEntry> entriesInFileOrder) {
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(buffer);
for (UnitTestZipEntry unitTestEntry : entriesInFileOrder) {
ZipEntry zipEntry = new ZipEntry(unitTestEntry.path);
zipOut.setLevel(unitTestEntry.level);
CRC32 crc32 = new CRC32();
byte[] uncompressedContent = unitTestEntry.getUncompressedBinaryContent();
crc32.update(uncompressedContent);
zipEntry.setCrc(crc32.getValue());
zipEntry.setSize(uncompressedContent.length);
if (unitTestEntry.level == 0) {
zipOut.setMethod(ZipOutputStream.STORED);
zipEntry.setCompressedSize(uncompressedContent.length);
} else {
zipOut.setMethod(ZipOutputStream.DEFLATED);
}
// Normalize MSDOS date/time fields to zero for reproducibility.
zipEntry.setTime(0);
if (unitTestEntry.comment != null) {
zipEntry.setComment(unitTestEntry.comment);
}
zipOut.putNextEntry(zipEntry);
zipOut.write(unitTestEntry.getUncompressedBinaryContent());
zipOut.closeEntry();
}
zipOut.close();
return buffer.toByteArray();
} catch (IOException e) {
// Should not happen as this is all in memory
throw new RuntimeException("Unable to generate test zip!", e);
}
}
protected static void makeCompressedFile(File folder, File compressedFile) throws IOException {
List<File> files = new ArrayList<>();
buildFileList(files, folder);
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
String absPath = folder.getAbsolutePath();
int folderLength = absPath.endsWith("/") ? absPath.length() : absPath.length() + 1;
int count;
ZipOutputStream outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(compressedFile)));
for (File file : files) {
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file), bufferSize);
ZipEntry entry = new ZipEntry(file.getAbsolutePath().substring(folderLength));
outputStream.putNextEntry(entry);
while ((count = inputStream.read(buffer, 0, bufferSize)) != -1) {
outputStream.write(buffer, 0, count);
}
inputStream.close();
outputStream.closeEntry();
}
outputStream.close();
}
private void createEmptyZipFile(File outputLocation) throws IOException {
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputLocation)));
zipOutputStream.close();
}
@Test
public void testZipSourceMultipleNestedDirs() throws Exception {
String buildSpecName = "buildspec.yml";
String dir1Name = "dir1";
String dir2Name = "dir2";
String dir3Name = "dir3";
String dir4Name = "dir4";
String dir5Name = "dir5";
String nestedFile4Name = "file.txt";
String nestedFile5Name = "log.txt";
File buildSpec = new File("/tmp/source/" + buildSpecName);
File dir1 = new File("/tmp/source/" + dir1Name); dir1.mkdir();
File dir2 = new File("/tmp/source/" + dir1Name + "/" + dir2Name); dir2.mkdir();
File dir3 = new File("/tmp/source/" + dir1Name + "/" + dir2Name + "/" + dir3Name); dir3.mkdir();
File dir4 = new File("/tmp/source/dir1/dir2/dir3/" + dir4Name); dir4.mkdir();
File dir5 = new File("/tmp/source/dir1/dir2/dir3/" + dir5Name); dir5.mkdir();
File file4 = new File("/tmp/source/dir1/dir2/dir3/dir4/" + nestedFile4Name);
File file5 = new File("/tmp/source/dir1/dir2/dir3/dir5/" + nestedFile5Name);
String buildSpecContents = "Hello!!!!!";
String nestedFile4Contents = "words";
String nestedFile5Contents = "logfile";
FileUtils.write(buildSpec, buildSpecContents);
FileUtils.write(file4, nestedFile4Contents);
FileUtils.write(file5, nestedFile5Contents);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream("/tmp/source.zip"));
ZipSourceCallable.zipSource(testZipSourceWorkspace, "/tmp/source/", out, "/tmp/source/");
out.close();
File zip = new File("/tmp/source.zip");
assertTrue(zip.exists());
File unzipFolder = new File("/tmp/folder/");
unzipFolder.mkdir();
ZipFile z = new ZipFile(zip.getPath());
z.extractAll(unzipFolder.getPath());
unzipFolder = new File("/tmp/folder/" + dir1Name);
assertTrue(unzipFolder.list().length == 1);
assertTrue(unzipFolder.list()[0].equals(dir2Name));
unzipFolder = new File("/tmp/folder/" + dir1Name + "/" + dir2Name);
assertTrue(unzipFolder.list().length == 1);
assertTrue(unzipFolder.list()[0].equals(dir3Name));
unzipFolder = new File("/tmp/folder/dir1/dir2/dir3/");
assertTrue(unzipFolder.list().length == 2);
unzipFolder = new File("/tmp/folder/dir1/dir2/dir3/dir4/");
assertTrue(unzipFolder.list().length == 1);
assertTrue(unzipFolder.list()[0].equals(nestedFile4Name));
unzipFolder = new File("/tmp/folder/dir1/dir2/dir3/dir5/");
assertTrue(unzipFolder.list().length == 1);
assertTrue(unzipFolder.list()[0].equals(nestedFile5Name));
}
/**
*
* @param variables
* @param rootDirectoryName
* @param createNewExpressionFilesXML
* @throws IOException
*/
public static void outputExpressionFilesXML(//
ValueModel[][] variables,
String rootDirectoryName,
boolean createNewExpressionFilesXML) throws IOException {
// drive ExpTreeII output from here
if (createNewExpressionFilesXML) {
MathMachineII.expFiles = new HashMap<>();
MathMachineII.rootDirectoryName = rootDirectoryName;
}
File rootDirectory = new File("." + File.separator + rootDirectoryName+File.separator);
if (rootDirectory.exists()) {
if (createNewExpressionFilesXML) {
// find and delete all .xml files
File[] expressionFilesXML = rootDirectory.listFiles(new FractionXMLFileFilter());
for (File f : expressionFilesXML) {
f.delete();
}
}
} else {
rootDirectory.mkdir();
}
FileOutputStream outputDirectoryDest = new FileOutputStream(rootDirectory+".zip");
ZipOutputStream output = new ZipOutputStream(outputDirectoryDest);
int BUFFER = 2048;
byte[] data = new byte[BUFFER];
for (ValueModel[] vms : variables) {
for (ValueModel valueModel : vms) {
FileInputStream input = new FileInputStream("."
+ File.separator
+ rootDirectoryName
+ File.separator
+ createPresentationFileVMs(valueModel.getValueTree(), valueModel.differenceValueCalcs()));
ZipEntry entry = new ZipEntry(valueModel.getName());
output.putNextEntry(entry);
BufferedInputStream in = new BufferedInputStream(input, BUFFER);
int count;
while ((count = in.read(data, 0, BUFFER)) != -1) {
output.write(data, 0, count);
}
output.closeEntry();
in.close();
}
}
output.close();
}
/**
* 压缩文件夹
* @param zipPath
* 生成的zip文件路径
* @param filePath
* 需要压缩的文件夹路径
* @throws Exception
*/
public static void zipFolder(String zipPath, String filePath) throws IOException {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));
File f = new File(filePath);
zipFiles(out, f, "");
out.close();
}
/**
* 压缩文件夹
* @param zipPath
* 生成的zip文件路径
* @param filePath
* 需要压缩的文件夹路径
* @throws Exception
*/
public static void zipFolder(String zipPath, String filePath) throws IOException {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));
File f = new File(filePath);
zipFiles(out, f, "");
out.close();
}