Java Tutorial/File/Zip Unzip — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 05:19, 1 июня 2010
Содержание
- 1 Compare two zip files
- 2 Compress a Byte Array
- 3 Compress Java objects
- 4 Compress string(byte array) by Deflater
- 5 Decompress a Byte Array
- 6 Decompress a zip file using ZipFile
- 7 Decompress Java objects
- 8 gzip
- 9 Put file To Zip File
- 10 Unpack an archive from a URL
- 11 Unpack a segment from a zip
- 12 Unzip
- 13 unzip File Into Directory
- 14 Uses Zip compression to compress any number of files given on the command line
- 15 Zip a list of file into one zip file.
- 16 Zip files
- 17 Zip up a directory
Compare two zip files
/* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
// From xml beans
public class ZipCompare {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: zipcompare [file1] [file2]");
System.exit(1);
}
ZipFile file1;
try {
file1 = new ZipFile(args[0]);
} catch (IOException e) {
System.out.println("Could not open zip file " + args[0] + ": " + e);
System.exit(1);
return;
}
ZipFile file2;
try {
file2 = new ZipFile(args[1]);
} catch (IOException e) {
System.out.println("Could not open zip file " + args[0] + ": " + e);
System.exit(1);
return;
}
System.out.println("Comparing " + args[0] + " with " + args[1] + ":");
Set set1 = new LinkedHashSet();
for (Enumeration e = file1.entries(); e.hasMoreElements();)
set1.add(((ZipEntry) e.nextElement()).getName());
Set set2 = new LinkedHashSet();
for (Enumeration e = file2.entries(); e.hasMoreElements();)
set2.add(((ZipEntry) e.nextElement()).getName());
int errcount = 0;
int filecount = 0;
for (Iterator i = set1.iterator(); i.hasNext();) {
String name = (String) i.next();
if (!set2.contains(name)) {
System.out.println(name + " not found in " + args[1]);
errcount += 1;
continue;
}
try {
set2.remove(name);
if (!streamsEqual(file1.getInputStream(file1.getEntry(name)), file2.getInputStream(file2
.getEntry(name)))) {
System.out.println(name + " does not match");
errcount += 1;
continue;
}
} catch (Exception e) {
System.out.println(name + ": IO Error " + e);
e.printStackTrace();
errcount += 1;
continue;
}
filecount += 1;
}
for (Iterator i = set2.iterator(); i.hasNext();) {
String name = (String) i.next();
System.out.println(name + " not found in " + args[0]);
errcount += 1;
}
System.out.println(filecount + " entries matched");
if (errcount > 0) {
System.out.println(errcount + " entries did not match");
System.exit(1);
}
System.exit(0);
}
static boolean streamsEqual(InputStream stream1, InputStream stream2) throws IOException {
byte[] buf1 = new byte[4096];
byte[] buf2 = new byte[4096];
boolean done1 = false;
boolean done2 = false;
try {
while (!done1) {
int off1 = 0;
int off2 = 0;
while (off1 < buf1.length) {
int count = stream1.read(buf1, off1, buf1.length - off1);
if (count < 0) {
done1 = true;
break;
}
off1 += count;
}
while (off2 < buf2.length) {
int count = stream2.read(buf2, off2, buf2.length - off2);
if (count < 0) {
done2 = true;
break;
}
off2 += count;
}
if (off1 != off2 || done1 != done2)
return false;
for (int i = 0; i < off1; i++) {
if (buf1[i] != buf2[i])
return false;
}
}
return true;
} finally {
stream1.close();
stream2.close();
}
}
}
Compress a Byte Array
import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] input = "asdf".getBytes();
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
compressor.setInput(input);
compressor.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
bos.close();
byte[] compressedData = bos.toByteArray();
}
}
Compress Java objects
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.zip.GZIPOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
User admin = new User();
admin.setId(new Long(1));
User foo = new User();
foo.setId(new Long(2));
ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(new File("user.dat"))));
oos.writeObject(admin);
oos.writeObject(foo);
oos.flush();
oos.close();
}
}
class User implements Serializable {
private Long id;
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("id=").append(id);
return sb.toString();
}
}
Compress string(byte array) by Deflater
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
public class Main {
public static void main(String[] args) throws IOException {
Deflater def = new Deflater();
byte[] input = new byte[1024];
byte[] output = new byte[1024];
FileInputStream fin = new FileInputStream("a.dat");
FileOutputStream fout = new FileOutputStream("b.dat");
int numRead = fin.read(input);
def.setInput(input, 0, numRead);
while (!def.needsInput()) {
int numCompressedBytes = def.deflate(output, 0, output.length);
if (numCompressedBytes > 0) {
fout.write(output, 0, numCompressedBytes);
}
}
def.finish();
fin.close();
fout.flush();
fout.close();
def.reset();
}
}
Decompress a Byte Array
import java.io.ByteArrayOutputStream;
import java.util.zip.Inflater;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] compressedData = null;
Inflater decompressor = new Inflater();
decompressor.setInput(compressedData);
ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);
byte[] buf = new byte[1024];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
bos.close();
byte[] decompressedData = bos.toByteArray();
}
}
Decompress a zip file using ZipFile
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Main {
public static void main(String[] args) throws Exception {
String zipname = "data.zip";
ZipFile zipFile = new ZipFile(zipname);
Enumeration enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
System.out.println("Unzipping: " + zipEntry.getName());
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
int size;
byte[] buffer = new byte[2048];
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(zipEntry.getName()), buffer.length);
while ((size = bis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, size);
}
bos.flush();
bos.close();
bis.close();
}
}
}
Decompress Java objects
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.zip.GZIPInputStream;
public class Main {
public static void main(String[] args) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new GZIPInputStream(new FileInputStream(new File(
"user.dat"))));
User admin = (User) ois.readObject();
User foo = (User) ois.readObject();
ois.close();
System.out.println("Admin = [" + admin + "]");
System.out.println("Foo = [" + foo + "]");
}
}
class User implements Serializable {
}
gzip
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
public class MainClass {
public final static String GZIP_SUFFIX = ".gz";
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
try {
InputStream fin = new FileInputStream(args[i]);
OutputStream fout = new FileOutputStream(args[i] + GZIP_SUFFIX);
GZIPOutputStream gzout = new GZIPOutputStream(fout);
for (int c = fin.read(); c != -1; c = fin.read()) {
gzout.write(c);
}
gzout.close();
} catch (IOException ex) {
System.err.println(ex);
}
}
}
}
Put file To Zip File
/*
* Copyright 2004 Outerthought bvba and Schaubroeck nv
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// revised from outerj daisy
import java.io.*;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
public class ZipHelper {
private static int BUFFER_SIZE = 32768;
public static void fileToZip(File file, File zipFile, int compressionLevel) throws Exception {
zipFile.createNewFile();
FileOutputStream fout = new FileOutputStream(zipFile);
ZipOutputStream zout = null;
try {
zout = new ZipOutputStream(new BufferedOutputStream(fout));
zout.setLevel(compressionLevel);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
fileToZip(files[i], zout, file);
} else if (file.isFile()) {
fileToZip(file, zout, file.getParentFile());
}
} finally {
if (zout != null)
zout.close();
}
}
private static void fileToZip(File file, ZipOutputStream zout, File baseDir) throws Exception {
String entryName = file.getPath().substring(baseDir.getPath().length() + 1);
if (File.separatorChar != "/")
entryName = entryName.replace(File.separator, "/");
if (file.isDirectory()) {
zout.putNextEntry(new ZipEntry(entryName + "/"));
zout.closeEntry();
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
fileToZip(files[i], zout, baseDir);
} else {
FileInputStream is = null;
try {
is = new FileInputStream(file);
zout.putNextEntry(new ZipEntry(entryName));
streamCopy(is, zout);
} finally {
zout.closeEntry();
if (is != null)
is.close();
}
}
}
private static void streamCopy(InputStream is, OutputStream os) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
}
}
}
Unpack an archive from a URL
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Utils {
/**
* Unpack an archive from a URL
*
* @param url
* @param targetDir
* @return the file to the url
* @throws IOException
*/
public static File unpackArchive(URL url, File targetDir) throws IOException {
if (!targetDir.exists()) {
targetDir.mkdirs();
}
InputStream in = new BufferedInputStream(url.openStream(), 1024);
// make sure we get the actual file
File zip = File.createTempFile("arc", ".zip", targetDir);
OutputStream out = new BufferedOutputStream(new FileOutputStream(zip));
copyInputStream(in, out);
out.close();
return unpackArchive(zip, targetDir);
}
/**
* Unpack a zip file
*
* @param theFile
* @param targetDir
* @return the file
* @throws IOException
*/
public static File unpackArchive(File theFile, File targetDir) throws IOException {
if (!theFile.exists()) {
throw new IOException(theFile.getAbsolutePath() + " does not exist");
}
if (!buildDirectory(targetDir)) {
throw new IOException("Could not create directory: " + targetDir);
}
ZipFile zipFile = new ZipFile(theFile);
for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
File file = new File(targetDir, File.separator + entry.getName());
if (!buildDirectory(file.getParentFile())) {
throw new IOException("Could not create directory: " + file.getParentFile());
}
if (!entry.isDirectory()) {
copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(file)));
} else {
if (!buildDirectory(file)) {
throw new IOException("Could not create directory: " + file);
}
}
}
zipFile.close();
return theFile;
}
public static void copyInputStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len >= 0) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
in.close();
out.close();
}
public static boolean buildDirectory(File file) {
return file.exists() || file.mkdirs();
}
}
Unpack a segment from a zip
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Utils {
/**
* unpack a segment from a zip
*
* @param addsi
* @param packetStream
* @param version
*/
public static void unpack(InputStream source, File destination) throws IOException {
ZipInputStream zin = new ZipInputStream(source);
ZipEntry zipEntry = null;
FileOutputStream fout = null;
byte[] buffer = new byte[4096];
while ((zipEntry = zin.getNextEntry()) != null) {
long ts = zipEntry.getTime();
// the zip entry needs to be a full path from the
// searchIndexDirectory... hence this is correct
File f = new File(destination, zipEntry.getName());
f.getParentFile().mkdirs();
fout = new FileOutputStream(f);
int len;
while ((len = zin.read(buffer)) > 0) {
fout.write(buffer, 0, len);
}
zin.closeEntry();
fout.close();
f.setLastModified(ts);
}
fout.close();
}
}
Unzip
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class MainClass {
public static void main(String[] args) throws IOException {
ZipFile zf = new ZipFile(args[0]);
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
System.out.println("Unzipping " + ze.getName());
FileOutputStream fout = new FileOutputStream(ze.getName());
InputStream in = zf.getInputStream(ze);
for (int c = in.read(); c != -1; c = in.read()) {
fout.write(c);
}
in.close();
fout.close();
}
}
}
unzip File Into Directory
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* @author csterling
*
*/
public class ZipFileUtil {
/**
* @param zipFile
* @param jiniHomeParentDir
*/
public static void unzipFileIntoDirectory(ZipFile zipFile, File jiniHomeParentDir) {
Enumeration files = zipFile.entries();
File f = null;
FileOutputStream fos = null;
while (files.hasMoreElements()) {
try {
ZipEntry entry = (ZipEntry) files.nextElement();
InputStream eis = zipFile.getInputStream(entry);
byte[] buffer = new byte[1024];
int bytesRead = 0;
f = new File(jiniHomeParentDir.getAbsolutePath() + File.separator + entry.getName());
if (entry.isDirectory()) {
f.mkdirs();
continue;
} else {
f.getParentFile().mkdirs();
f.createNewFile();
}
fos = new FileOutputStream(f);
while ((bytesRead = eis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
continue;
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// ignore
}
}
}
}
}
}
Uses Zip compression to compress any number of files given on the command line
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class MainClass {
public static void main(String[] args) throws IOException {
FileOutputStream f = new FileOutputStream("test.zip");
CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
ZipOutputStream zos = new ZipOutputStream(csum);
BufferedOutputStream out = new BufferedOutputStream(zos);
zos.setComment("A test of Java Zipping");
for (int i = 0; i < args.length; i++) {
System.out.println("Writing file " + args[i]);
BufferedReader in = new BufferedReader(new FileReader(args[i]));
zos.putNextEntry(new ZipEntry(args[i]));
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
}
out.close();
System.out.println("Checksum: " + csum.getChecksum().getValue());
System.out.println("Reading file");
FileInputStream fi = new FileInputStream("test.zip");
CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
ZipInputStream in2 = new ZipInputStream(csumi);
BufferedInputStream bis = new BufferedInputStream(in2);
ZipEntry ze;
while ((ze = in2.getNextEntry()) != null) {
System.out.println("Reading file " + ze);
int x;
while ((x = bis.read()) != -1)
System.out.write(x);
}
System.out.println("Checksum: " + csumi.getChecksum().getValue());
bis.close();
}
}
Zip a list of file into one zip file.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Utils {
/**
* Zip a list of file into one zip file.
*
* @param files
* files to zip
* @param targetZipFile
* target zip file
* @throws IOException
* IO error exception can be thrown when copying ...
*/
public static void zipFile(final File[] files, final File targetZipFile) throws IOException {
try {
FileOutputStream fos = new FileOutputStream(targetZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
byte[] buffer = new byte[128];
for (int i = 0; i < files.length; i++) {
File currentFile = files[i];
if (!currentFile.isDirectory()) {
ZipEntry entry = new ZipEntry(currentFile.getName());
FileInputStream fis = new FileInputStream(currentFile);
zos.putNextEntry(entry);
int read = 0;
while ((read = fis.read(buffer)) != -1) {
zos.write(buffer, 0, read);
}
zos.closeEntry();
fis.close();
}
}
zos.close();
fos.close();
} catch (FileNotFoundException e) {
System.out.println("File not found : " + e);
}
}
}
Zip files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class MainClass {
public static void main(String[] args) throws IOException {
String outputFile = "new.zip";
// Default to maximum compression
int level = 9;
int start = 1;
FileOutputStream fout = new FileOutputStream(outputFile);
ZipOutputStream zout = new ZipOutputStream(fout);
zout.setLevel(level);
for (int i = start; i < args.length; i++) {
ZipEntry ze = new ZipEntry(args[i]);
FileInputStream fin = new FileInputStream(args[i]);
try {
System.out.println("Compressing " + args[i]);
zout.putNextEntry(ze);
for (int c = fin.read(); c != -1; c = fin.read()) {
zout.write(c);
}
} finally {
fin.close();
}
}
zout.close();
}
}
Zip up a directory
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* File utilities
*
* @version $Revision: 691982 $
*/
public final class FileUtil {
/**
* Zip up a directory
*
* @param directory
* @param zipName
* @throws IOException
*/
public static void zipDir(String directory, String zipName) throws IOException {
// create a ZipOutputStream to zip the data to
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipName));
String path = "";
zipDir(directory, zos, path);
// close the stream
zos.close();
}
/**
* Zip up a directory path
* @param directory
* @param zos
* @param path
* @throws IOException
*/
public static void zipDir(String directory, ZipOutputStream zos, String path) throws IOException {
File zipDir = new File(directory);
// get a listing of the directory content
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
// loop through dirList, and zip the files
for (int i = 0; i < dirList.length; i++) {
File f = new File(zipDir, dirList[i]);
if (f.isDirectory()) {
String filePath = f.getPath();
zipDir(filePath, zos, path + f.getName() + "/");
continue;
}
FileInputStream fis = new FileInputStream(f);
try {
ZipEntry anEntry = new ZipEntry(path + f.getName());
zos.putNextEntry(anEntry);
bytesIn = fis.read(readBuffer);
while (bytesIn != -1) {
zos.write(readBuffer, 0, bytesIn);
bytesIn = fis.read(readBuffer);
}
} finally {
fis.close();
}
}
}
}