下面列出了怎么用java.util.zip.ZipException的API类实例代码及写法,或者点击链接到github查看源代码。
private boolean processTrailer() throws ZipException {
if (inflater != null
&& gzipMetadataReader.readableBytes() <= GZIP_HEADER_MIN_SIZE + GZIP_TRAILER_SIZE) {
// We don't have enough bytes to begin inflating a concatenated gzip stream, drop context
inflater.end();
inflater = null;
}
if (gzipMetadataReader.readableBytes() < GZIP_TRAILER_SIZE) {
return false;
}
if (crc.getValue() != gzipMetadataReader.readUnsignedInt()
|| expectedGzipTrailerIsize != gzipMetadataReader.readUnsignedInt()) {
throw new ZipException("Corrupt GZIP trailer");
}
crc.reset();
state = State.HEADER;
return true;
}
public static NBTTagCompound readNBT(File file) throws IOException {
if (!file.exists()) {
return null;
}
FileInputStream in = new FileInputStream(file);
NBTTagCompound tag;
try {
tag = CompressedStreamTools.readCompressed(in);
} catch (ZipException e) {
if (e.getMessage().equals("Not in GZIP format")) {
tag = CompressedStreamTools.read(file);
} else {
throw e;
}
}
in.close();
return tag;
}
@Override
public void write(byte b[], int off, int len) throws IOException {
if (e.type != Entry.FILECH) // only from sync
ensureOpen();
if (off < 0 || len < 0 || off > b.length - len) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
switch (e.method) {
case METHOD_DEFLATED:
super.write(b, off, len);
break;
case METHOD_STORED:
written += len;
out.write(b, off, len);
break;
default:
throw new ZipException("invalid compression method");
}
crc.update(b, off, len);
}
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
if (verbose) {
System.err.println("JarBuilder.addNamedStream " + name);
}
try {
dst.putNextEntry(new JarEntry(name));
int bytesRead = 0;
while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
dst.write(buffer, 0, bytesRead);
}
} catch (ZipException ze) {
if (ze.getMessage().indexOf("duplicate entry") >= 0) {
if (verbose) {
System.err.println(ze + " Skip duplicate entry " + name);
}
} else {
throw ze;
}
} finally {
in.close();
dst.flush();
dst.closeEntry();
}
}
public void deleteFile(byte[] path, boolean failIfNotExists)
throws IOException
{
checkWritable();
IndexNode inode = getInode(path);
if (inode == null) {
if (path != null && path.length == 0)
throw new ZipException("root directory </> can't not be delete");
if (failIfNotExists)
throw new NoSuchFileException(getString(path));
} else {
if (inode.isDir() && inode.child != null)
throw new DirectoryNotEmptyException(getString(path));
updateDelete(inode);
}
}
@Override
public void write(byte b[], int off, int len) throws IOException {
if (e.type != Entry.FILECH) // only from sync
ensureOpen();
if (off < 0 || len < 0 || off > b.length - len) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
switch (e.method) {
case METHOD_DEFLATED:
super.write(b, off, len);
break;
case METHOD_STORED:
written += len;
out.write(b, off, len);
break;
default:
throw new ZipException("invalid compression method");
}
crc.update(b, off, len);
}
public void deleteFile(byte[] path, boolean failIfNotExists)
throws IOException
{
checkWritable();
IndexNode inode = getInode(path);
if (inode == null) {
if (path != null && path.length == 0)
throw new ZipException("root directory </> can't not be delete");
if (failIfNotExists)
throw new NoSuchFileException(getString(path));
} else {
if (inode.isDir() && inode.child != null)
throw new DirectoryNotEmptyException(getString(path));
updateDelete(inode);
}
}
private boolean processTrailer() throws ZipException {
if (inflater != null
&& gzipMetadataReader.readableBytes() <= GZIP_HEADER_MIN_SIZE + GZIP_TRAILER_SIZE) {
// We don't have enough bytes to begin inflating a concatenated gzip stream, drop context
inflater.end();
inflater = null;
}
if (gzipMetadataReader.readableBytes() < GZIP_TRAILER_SIZE) {
return false;
}
if (crc.getValue() != gzipMetadataReader.readUnsignedInt()
|| expectedGzipTrailerIsize != gzipMetadataReader.readUnsignedInt()) {
throw new ZipException("Corrupt GZIP trailer");
}
crc.reset();
state = State.HEADER;
return true;
}
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
if (verbose) {
System.err.println("JarBuilder.addNamedStream " + name);
}
try {
dst.putNextEntry(new JarEntry(name));
int bytesRead = 0;
while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
dst.write(buffer, 0, bytesRead);
}
} catch (ZipException ze) {
if (ze.getMessage().indexOf("duplicate entry") >= 0) {
if (verbose) {
System.err.println(ze + " Skip duplicate entry " + name);
}
} else {
throw ze;
}
} finally {
in.close();
dst.flush();
dst.closeEntry();
}
}
private void loadJarsToLocations() throws ZipException, IOException{
for(File zfa : this.jdkjars){
ZipFile zf = new ZipFile(zfa);
Enumeration<?> entries = zf.entries();
while(entries.hasMoreElements()){
ZipEntry ze = (ZipEntry)entries.nextElement();
if(!ze.isDirectory()){
String name = ze.getName();
if(name.endsWith(".class")){
name = name.substring(0, name.length()-6);
nameToLocation.put(name, new FileAndZipEntry(zf, ze));
}
}
}
}
}
private boolean read_trailer_() throws IOException {
final int crc_value = (int)crc_.getValue();
final int declared_crc = read_int_();
LOG.log(Level.FINE, "crc = {0}, expecting {1}", new Object[]{crc_value, declared_crc});
if (declared_crc != crc_value)
throw new ZipException("CRC mismatch");
final int declared_fsize = read_int_();
LOG.log(Level.FINE, "fsize (modulo int) = {0}, expecting {1}", new Object[]{(int)(inflater_.getBytesWritten() & 0xffffffff), declared_fsize});
if ((int)(inflater_.getBytesWritten() & 0xffffffff) != declared_fsize)
throw new ZipException("File size check mismatch");
if (raw_.atEof()) return true; // End-of-stream.
// Not at end of stream, assume gzip concatenation.
read_header_();
return false;
}
String addDirectoryToJar(final JarOutputStream jar, final String outputDirectory) throws IOException {
// format the output directory
String formattedOutputDirectory = "";
if (outputDirectory != null && !outputDirectory.isEmpty()) {
if (!outputDirectory.endsWith("/")) {
formattedOutputDirectory = outputDirectory + File.separatorChar;
} else {
formattedOutputDirectory = outputDirectory;
}
}
if (!formattedOutputDirectory.isEmpty()) {
try {
jar.putNextEntry(new ZipEntry(formattedOutputDirectory));
jar.closeEntry();
} catch (final ZipException ignore) {} // ignore duplicate entries and other errors
}
return formattedOutputDirectory;
}
public void deleteFile(byte[] path, boolean failIfNotExists)
throws IOException
{
checkWritable();
IndexNode inode = getInode(path);
if (inode == null) {
if (path != null && path.length == 0)
throw new ZipException("root directory </> can't not be delete");
if (failIfNotExists)
throw new NoSuchFileException(getString(path));
} else {
if (inode.isDir() && inode.child != null)
throw new DirectoryNotEmptyException(getString(path));
updateDelete(inode);
}
}
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
if (verbose) {
System.err.println("JarBuilder.addNamedStream " + name);
}
try {
dst.putNextEntry(new JarEntry(name));
int bytesRead = 0;
while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
dst.write(buffer, 0, bytesRead);
}
} catch (ZipException ze) {
if (ze.getMessage().indexOf("duplicate entry") >= 0) {
if (verbose) {
System.err.println(ze + " Skip duplicate entry " + name);
}
} else {
throw ze;
}
} finally {
in.close();
dst.flush();
dst.closeEntry();
}
}
/**
* Generates the raw byte data of the end of central directory record for the specified
* {@link ZipFileData}.
* @throws ZipException if the file comment is too long
*/
static byte[] create(ZipFileData file, boolean allowZip64) throws ZipException {
byte[] comment = file.getBytes(file.getComment());
byte[] buf = new byte[FIXED_DATA_SIZE + comment.length];
// Allow writing of Zip file without Zip64 extensions for large archives as a special case
// since many reading implementations can handle this.
short numEntries = (short) (file.getNumEntries() > 0xffff && allowZip64
? -1 : file.getNumEntries());
int cdSize = (int) (file.getCentralDirectorySize() > 0xffffffffL && allowZip64
? -1 : file.getCentralDirectorySize());
int cdOffset = (int) (file.getCentralDirectoryOffset() > 0xffffffffL && allowZip64
? -1 : file.getCentralDirectoryOffset());
ZipUtil.intToLittleEndian(buf, SIGNATURE_OFFSET, SIGNATURE);
ZipUtil.shortToLittleEndian(buf, DISK_NUMBER_OFFSET, (short) 0);
ZipUtil.shortToLittleEndian(buf, CD_DISK_OFFSET, (short) 0);
ZipUtil.shortToLittleEndian(buf, DISK_ENTRIES_OFFSET, numEntries);
ZipUtil.shortToLittleEndian(buf, TOTAL_ENTRIES_OFFSET, numEntries);
ZipUtil.intToLittleEndian(buf, CD_SIZE_OFFSET, cdSize);
ZipUtil.intToLittleEndian(buf, CD_OFFSET_OFFSET, cdOffset);
ZipUtil.shortToLittleEndian(buf, COMMENT_LENGTH_OFFSET, (short) comment.length);
System.arraycopy(comment, 0, buf, FIXED_DATA_SIZE, comment.length);
return buf;
}
public void deleteFile(byte[] path, boolean failIfNotExists)
throws IOException
{
checkWritable();
IndexNode inode = getInode(path);
if (inode == null) {
if (path != null && path.length == 0)
throw new ZipException("root directory </> can't not be delete");
if (failIfNotExists)
throw new NoSuchFileException(getString(path));
} else {
if (inode.isDir() && inode.child != null)
throw new DirectoryNotEmptyException(getString(path));
updateDelete(inode);
}
}
public void deleteFile(byte[] path, boolean failIfNotExists)
throws IOException
{
checkWritable();
IndexNode inode = getInode(path);
if (inode == null) {
if (path != null && path.length == 0)
throw new ZipException("root directory </> can't not be delete");
if (failIfNotExists)
throw new NoSuchFileException(getString(path));
} else {
if (inode.isDir() && inode.child != null)
throw new DirectoryNotEmptyException(getString(path));
updateDelete(inode);
}
}
private byte[] readBytes(Entry entry) throws IOException {
byte[] header = getHeader(entry);
int csize = entry.compressedSize;
byte[] cbuf = new byte[csize];
zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28));
zipRandomFile.readFully(cbuf, 0, csize);
// is this compressed - offset 8 in the ZipEntry header
if (get2ByteLittleEndian(header, 8) == 0)
return cbuf;
int size = entry.size;
byte[] buf = new byte[size];
if (inflate(cbuf, buf) != size)
throw new ZipException("corrupted zip file");
return buf;
}
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
if (verbose) {
System.err.println("JarBuilder.addNamedStream " + name);
}
try {
dst.putNextEntry(new JarEntry(name));
int bytesRead = 0;
while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
dst.write(buffer, 0, bytesRead);
}
} catch (ZipException ze) {
if (ze.getMessage().indexOf("duplicate entry") >= 0) {
if (verbose) {
System.err.println(ze + " Skip duplicate entry " + name);
}
} else {
throw ze;
}
} finally {
in.close();
dst.flush();
dst.closeEntry();
}
}
private byte[] readBytes(Entry entry) throws IOException {
byte[] header = getHeader(entry);
int csize = entry.compressedSize;
byte[] cbuf = new byte[csize];
zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28));
zipRandomFile.readFully(cbuf, 0, csize);
// is this compressed - offset 8 in the ZipEntry header
if (get2ByteLittleEndian(header, 8) == 0)
return cbuf;
int size = entry.size;
byte[] buf = new byte[size];
if (inflate(cbuf, buf) != size)
throw new ZipException("corrupted zip file");
return buf;
}
/**
* Generates the raw byte data of the central directory file header for the ZipEntry. Uses the
* specified {@link ZipFileData} to encode the file name and comment.
* @throws ZipException
*/
static byte[] create(ZipFileEntry entry, ZipFileData file, boolean allowZip64)
throws ZipException {
if (allowZip64) {
addZip64Extra(entry);
} else {
entry.getExtra().remove((short) 0x0001);
}
byte[] name = file.getBytes(entry.getName());
byte[] extra = entry.getExtra().getBytes();
byte[] comment = entry.getComment() != null
? file.getBytes(entry.getComment()) : new byte[]{};
byte[] buf = new byte[FIXED_DATA_SIZE + name.length + extra.length + comment.length];
fillFixedSizeData(buf, entry, name.length, extra.length, comment.length, allowZip64);
System.arraycopy(name, 0, buf, FIXED_DATA_SIZE, name.length);
System.arraycopy(extra, 0, buf, FIXED_DATA_SIZE + name.length, extra.length);
System.arraycopy(comment, 0, buf, FIXED_DATA_SIZE + name.length + extra.length,
comment.length);
return buf;
}
@Test public void testPrefixFileAfterZip() throws IOException {
try (ZipWriter writer = new ZipWriter(new FileOutputStream(test), UTF_8)) {
byte[] content = "content".getBytes(UTF_8);
crc.update(content);
ZipFileEntry entry = new ZipFileEntry("foo");
entry.setSize(content.length);
entry.setCompressedSize(content.length);
entry.setCrc(crc.getValue());
entry.setTime(cal.getTimeInMillis());
writer.putNextEntry(entry);
thrown.expect(ZipException.class);
thrown.expectMessage("Cannot add a prefix file after the zip contents have been started.");
writer.startPrefixFile();
}
}
static ClassPathElement getClassPathElement(File file)
throws ZipException, IOException {
if (file.isDirectory()) {
return new FolderPathElement(file);
} else if (file.isFile()) {
return new ArchivePathElement(new ZipFile(file));
} else if (file.exists()) {
throw new IOException("\"" + file.getPath() +
"\" is not a directory neither a zip file");
} else {
throw new FileNotFoundException("File \"" + file.getPath() + "\" not found");
}
}
@SuppressWarnings("deprecation")
private List<URL> handleZipFile(File file) throws IOException
{
File tempDir = OperatingSystemUtils.createTempDir();
List<URL> result = new ArrayList<>();
try
{
ZipFile zip = new ZipFile(file);
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements())
{
ZipEntry entry = entries.nextElement();
String name = entry.getName();
if (name.matches(path + "/.*\\.jar"))
{
log.log(Level.FINE, String.format("ZipEntry detected: %s len %d added %TD",
file.getAbsolutePath() + "/" + entry.getName(), entry.getSize(),
new Date(entry.getTime())));
result.add(copy(tempDir, entry.getName(),
JarLocator.class.getClassLoader().getResource(name).openStream()
).toURL());
}
}
zip.close();
}
catch (ZipException e)
{
throw new RuntimeException("Error handling file " + file, e);
}
return result;
}
/**
* Test if the target path is an archive.
* @param path path to the file.
* @return true if the path points to a zip file - false otherwise.
* @throws IOException
*/
public static final boolean isArchive(Path path) throws IOException {
if (Files.exists(path) && Files.isRegularFile(path)) {
try (ZipFile zip = new ZipFile(path.toFile())){
return true;
} catch (ZipException e) {
return false;
}
}
return false;
}
private void readEnd(ZipEntry e) throws IOException {
int n = this.inf.getRemaining();
if (n > 0) {
((PushbackInputStream) this.in).unread(this.buf, this.len - n, n);
}
if ((e.flag & 0x8) == 8) {
readFully(this.tmpbuf, 0, 16);
long sig = get32(this.tmpbuf, 0);
if (sig != 134695760L) {
e.crc = sig;
e.csize = get32(this.tmpbuf, 4);
e.size = get32(this.tmpbuf, 8);
((PushbackInputStream) this.in).unread(this.tmpbuf, 11, 4);
} else {
e.crc = get32(this.tmpbuf, 4);
e.csize = get32(this.tmpbuf, 8);
e.size = get32(this.tmpbuf, 12);
}
}
if (e.size != this.inf.getTotalOut()) {
throw new ZipException("invalid entry size (expected " + e.size
+ " but got " + this.inf.getTotalOut() + " bytes)");
}
if (e.csize != this.inf.getTotalIn()) {
throw new ZipException("invalid entry compressed size (expected "
+ e.csize + " but got " + this.inf.getTotalIn() + " bytes)");
}
if (e.crc != this.crc.getValue())
throw new ZipException("invalid entry CRC (expected 0x"
+ Long.toHexString(e.crc) + " but got 0x"
+ Long.toHexString(this.crc.getValue()) + ")");
}
private InputStream getInputStream() throws IOException {
long start = calcDataOffset();
BoundedInputStream bis = new BoundedInputStream(start, getCompressedSize());
switch (getMethod()) {
case ZipEntry.STORED:
return bis;
case ZipEntry.DEFLATED:
bis.addDummy();
return new InflaterInputStream(bis, new Inflater(true));
default:
throw new ZipException("Found unsupported compression method " + getMethod());
}
}
public Path unzipInTempDir(InputStream is, String tempDirPrefix) throws IOException {
Path tempDirectory = Files.createTempDirectory(temporaryZipPath, tempDirPrefix);
Path zipFile = writeInDir(is, tempDirectory);
try {
ZipUtil.unpack(zipFile.toFile(), tempDirectory.toFile());
} catch (org.zeroturnaround.zip.ZipException e) {
throw new ZipException(e.getMessage());
} finally {
FileUtils.deleteQuietly(zipFile.toFile());
}
return tempDirectory;
}
static ClassPathElement getClassPathElement(File file)
throws ZipException, IOException {
if (file.isDirectory()) {
return new FolderPathElement(file);
} else if (file.isFile()) {
return new ArchivePathElement(new ZipFile(file));
} else if (file.exists()) {
throw new IOException("\"" + file.getPath() +
"\" is not a directory neither a zip file");
} else {
throw new FileNotFoundException("File \"" + file.getPath() + "\" not found");
}
}
/**
* 解压文件名包含传入文字的文件
*
* @param zipFile 压缩文件
* @param folderPath 目标文件夹
* @param nameContains 传入的文件匹配名
* @throws ZipException 压缩格式有误时抛出
* @throws IOException IO错误时抛出
*/
public static ArrayList<File> upZipSelectedFile(File zipFile, String folderPath,
String nameContains) throws ZipException, IOException {
ArrayList<File> fileList = new ArrayList<File>();
File desDir = new File(folderPath);
if (!desDir.exists()) {
desDir.mkdir();
}
ZipFile zf = new ZipFile(zipFile);
for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
ZipEntry entry = ((ZipEntry)entries.nextElement());
if (entry.getName().contains(nameContains)) {
InputStream in = zf.getInputStream(entry);
String str = folderPath + File.separator + entry.getName();
str = new String(str.getBytes("8859_1"), "GB2312");
// str.getBytes("GB2312"),"8859_1" 输出
// str.getBytes("8859_1"),"GB2312" 输入
File desFile = new File(str);
if (!desFile.exists()) {
File fileParentDir = desFile.getParentFile();
if (!fileParentDir.exists()) {
fileParentDir.mkdirs();
}
desFile.createNewFile();
}
OutputStream out = new FileOutputStream(desFile);
byte buffer[] = new byte[BUFF_SIZE];
int realLength;
while ((realLength = in.read(buffer)) > 0) {
out.write(buffer, 0, realLength);
}
in.close();
out.close();
fileList.add(desFile);
}
}
return fileList;
}