下面列出了java.util.zip.ZipInputStream#read ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void unzip(InputStream source, File destDir) throws IOException {
Utilities.createDirectory(destDir.getAbsolutePath());
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(source);
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = newFile(destDir, zipEntry);
if (zipEntry.isDirectory()) {
Utilities.createDirectory(newFile.getAbsolutePath());
} else {
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
private Map<String, InputStream> readInputStream(InputStream stream) throws IOException {
Map<String, InputStream> res = new HashMap<String, InputStream>();
ZipInputStream zip = new ZipInputStream(stream);
ZipEntry ze = null;
while ((ze = zip.getNextEntry()) != null) {
String n = ze.getName();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
for (int c = zip.read(); c != -1; c = zip.read()) {
bs.write(c);
}
bs.close();
res.put(n, new ByteArrayInputStream(bs.toByteArray()));
zip.closeEntry();
}
zip.close();
return res;
}
private byte[] readByteArray(ZipInputStream zip, int expected) throws IOException {
if (expected == -1) { // unknown size
return IOUtils.toByteArray(zip);
}
final byte[] bytes = new byte[expected];
int read = 0;
do {
int n = zip.read(bytes, read, expected - read);
if (n <= 0) {
break;
}
read += n;
} while (read < expected);
if (expected != bytes.length) {
throw new EOFException("unexpected EOF");
}
return bytes;
}
private void updateGuidZipEntryMap() throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
String entryName = zipEntry.getName().replace(".json", "");
if (guidEntityJsonMap.containsKey(entryName)) continue;
byte[] buf = new byte[1024];
int n = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((n = zipInputStream.read(buf, 0, 1024)) > -1) {
bos.write(buf, 0, n);
}
guidEntityJsonMap.put(entryName, bos.toString());
zipEntry = zipInputStream.getNextEntry();
}
zipInputStream.close();
}
private void updateGuidZipEntryMap() throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
String entryName = zipEntry.getName().replace(".json", "");
if (guidEntityJsonMap.containsKey(entryName)) continue;
byte[] buf = new byte[1024];
int n = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((n = zipInputStream.read(buf, 0, 1024)) > -1) {
bos.write(buf, 0, n);
}
guidEntityJsonMap.put(entryName, bos.toString());
zipEntry = zipInputStream.getNextEntry();
}
zipInputStream.close();
}
/**
* It's better NOT TO USE THIS METHOD, since it creates a temporary file.
* Use {@link IOUtils#unzipUniqueFileAsStream()} instead
*
* @param inFile
* a zip file containing a unique file
* @return the unique file through a temporary file
*/
public static File unzipUniqueFile(File inFile) throws IOException {
File outFile = File.createTempFile(inFile.getName(), "tmp");
try {
BufferedOutputStream out = null;
ZipInputStream in = new ZipInputStream(new BufferedInputStream(
new FileInputStream(inFile)));
in.getNextEntry();
int count;
byte data[] = new byte[1024];
out = new BufferedOutputStream(new FileOutputStream(outFile), 1024);
while ((count = in.read(data, 0, 1024)) != -1) {
out.write(data, 0, count);
}
out.flush();
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return outFile;
}
private static void copy(final ZipInputStream zis,
final FileOutputStream fos) throws IOException {
final byte[] buff = new byte[1024 * 64];
int r;
while ((r = zis.read(buff)) > 0) {
fos.write(buff, 0, r);
}
}
public static void unZip(String zipFile, String targetDir) {
int BUFFER = 4096; //这里缓冲区我们使用4KB,
String strEntry; //保存每个zip的条目名称
try {
BufferedOutputStream dest = null; //缓冲输出流
FileInputStream fis = new FileInputStream(zipFile);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry; //每个zip条目的实例
while ((entry = zis.getNextEntry()) != null) {
try {
Log.i("Unzip: ", "=" + entry);
int count;
byte data[] = new byte[BUFFER];
strEntry = entry.getName();
File entryFile = new File(targetDir + strEntry);
File entryDir = new File(entryFile.getParent());
if (!entryDir.exists()) {
entryDir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(entryFile);
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
zis.close();
} catch (Exception cwj) {
cwj.printStackTrace();
}
}
private static void extractFile(ZipInputStream zipIn, File file) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
public static void unzipToFolder(File zipFile, File outputFolder) throws IOException {
outputFolder.mkdirs();
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
byte[] buffer = new byte[1024 * 4];
while(ze!=null){
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
if(ze.isDirectory()) {
newFile.mkdirs();
} else {
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
private static void unzip(ZipInputStream zis, String basePath) throws IOException {
ZipEntry entry = zis.getNextEntry();
if (entry != null) {
// File file = new File(basePath + File.separator + entry.getName());
File file = new File(basePath + entry.getName());
if (file.isDirectory()) {
// 可能存在空文件夹
if (!file.exists())
file.mkdirs();
unzip(zis, basePath);
} else {
File parentFile = file.getParentFile();
if (parentFile != null && !parentFile.exists())
parentFile.mkdirs();
FileOutputStream fos = new FileOutputStream(file);// 输出流创建文件时必须保证父路径存在
int len = 0;
byte[] buf = new byte[1024];
while ((len = zis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
fos.close();
zis.closeEntry();
unzip(zis, basePath);
}
}
}
private static void extractFile(ZipInputStream in, File outdir, String name) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir, name)));
int count = -1;
while ((count = in.read(buffer)) != -1)
out.write(buffer, 0, count);
out.close();
}
public static void upZipFile(Context context,String assetPath,String outputFolderPath){
File desDir = new File(outputFolderPath);
if (!desDir.isDirectory()) {
desDir.mkdirs();
}
try {
InputStream inputStream = context.getResources().getAssets().open(assetPath);
ZipInputStream zipInputStream=new ZipInputStream(inputStream);
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
Log.d(TAG, "upZipFile: "+zipEntry.getName());
if(zipEntry.isDirectory()) {
File tmpFile=new File(outputFolderPath,zipEntry.getName());
//Log.d(TAG, "upZipFile: folder "+tmpFile.getAbsolutePath());
if(!tmpFile.isDirectory())
tmpFile.mkdirs();
} else {
File desFile = new File(outputFolderPath +"/"+ zipEntry.getName());
if(desFile.exists()) continue;
OutputStream out = new FileOutputStream(desFile);
//Log.d(TAG, "upZipFile: "+desFile.getAbsolutePath());
byte buffer[] = new byte[1024];
int realLength;
while ((realLength = zipInputStream.read(buffer)) > 0) {
out.write(buffer, 0, realLength);
}
zipInputStream.closeEntry();
out.close();
}
}
zipInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static <T extends Command> T fromBytes(byte[] bytes) throws IOException {
ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(bytes));
ZipEntry ze = zin.getNextEntry();
if(ze == null){
throw new AsyncException("something is seriously wrong with serialization");
}
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len;
while((len = zin.read(buffer)) != -1) {
bout.write(buffer, 0, len);
}
return (T) Command.fromXml(bout.toString());
}
public static boolean unpackZip(File zipFile, File destFolder) {
try {
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
String filename;
while ((ze = zipInputStream.getNextEntry()) != null) {
// zapis do souboru
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
File fmd = new File(destFolder, filename);
fmd.mkdirs();
continue;
}
File outFile = new File(destFolder, filename);
System.out.println("out = " + outFile);
FileOutputStream fout = new FileOutputStream(outFile);
// cteni zipu a zapis
while ((count = zipInputStream.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
zipInputStream.closeEntry();
}
zipInputStream.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Extract compressed directory to given path
* @param zipentry the compressed directory to extract
* @param zipFile the file containing the compressed directory
* @param extractionpath the path where to extract the directory
* @return List of extracted directories and file
* @throws Exception
*/
private StringBuilder extractDir(ZipEntry zipentry, String zipFile,String extractionpath) throws Exception {
byte[] buf = new byte[8128];
int n;
String entryName;
String rootPath = zipentry.getName();
//Cleanup name by using generic path separator and
rootPath = rootPath.replace('\\', '/');
File newFile = new File(extractionpath+rootPath);
newFile.mkdirs();
if (debug)System.out.println("creating repository:"+newFile);
//lets inspect the zip file
ZipInputStream zipinputstream = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
BufferedOutputStream bos;
StringBuilder directoriesList = new StringBuilder();
StringBuilder fileList = new StringBuilder();
while ( (zipentry = zipinputstream.getNextEntry()) != null) {
//for each entry to be extracted
entryName = zipentry.getName();
//Cleanup name by using generic path separator and
entryName = entryName.replace('\\', '/');
if (debug)System.out.println("extracting:"+entryName);
//check that entry match library path
if (!entryName.startsWith(rootPath) || entryName.contains("..")) {
if (debug) System.out.println("SKIP: entryname: ["+entryName+ "] ==> [" + rootPath +"]");
zipinputstream.closeEntry();
continue;
}
newFile = new File(entryName);
if (newFile.exists()){
zipinputstream.closeEntry();
message.append(entryName).append("\n");
continue;
}
//if entry is a path, just create it
if (entryName.endsWith("/")){
if (debug)System.out.println("Entry is a path - creating it: "+entryName);
File destfile = new File(extractionpath+entryName);
destfile.mkdirs();
directoriesList.append(extractionpath).append(entryName).append("\n");
continue;
} else {
//extract file content
bos = new BufferedOutputStream(new FileOutputStream(extractionpath+entryName));
while ((n = zipinputstream.read(buf)) > -1){
bos.write(buf, 0, n);
}
if (debug)System.out.println("Entry is a file - extracting it to "+extractionpath+entryName);
bos.close();
fileList.append(extractionpath).append(entryName).append("\n");
}
//close entry
zipinputstream.closeEntry();
}//while
zipinputstream.close();
return fileList.append(directoriesList);
}
public static void unzip(InputStream is, String dir) throws IOException {
File dest = new File(dir);
if (!dest.exists()) {
dest.mkdirs();
}
if (!dest.isDirectory())
throw new IOException("Invalid Unzip destination " + dest);
if (null == is) {
throw new IOException("InputStream is null");
}
ZipInputStream zip = new ZipInputStream(is);
ZipEntry ze;
while ((ze = zip.getNextEntry()) != null) {
final String path = dest.getAbsolutePath()
+ File.separator + ze.getName();
String zeName = ze.getName();
char cTail = zeName.charAt(zeName.length() - 1);
if (cTail == File.separatorChar) {
File file = new File(path);
if (!file.exists()) {
if (!file.mkdirs()) {
throw new IOException("Unable to create folder " + file);
}
}
continue;
}
FileOutputStream fout = new FileOutputStream(path);
byte[] bytes = new byte[1024];
int c;
while ((c = zip.read(bytes)) != -1) {
fout.write(bytes, 0, c);
}
zip.closeEntry();
fout.close();
}
}
/**
* <p>
* This method reads the current entry from a zip and returns the bytes
* </p>
*
* @param inputStream
* Zip Input stream
* @return bytes from the current entry in the zip file
* @throws FileNotFoundException
* error occurred
* @throws IOException
* error occurred
*/
public static byte[] getEntryBytesFromZip(ZipInputStream inputStream)
throws IOException {
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
int el;
byte[] buffer = new byte[1 << InstrumentConstants.FIFTEEN];
while ((el = inputStream.read(buffer)) != -1) {
byteArray.write(buffer, 0, el);
}
return byteArray.toByteArray();
}