use of java.util.zip.ZipException in project javautils by jiadongpo.
the class FileUtil method unZipRedirect.
/**
* 传入压缩包路径,解压,取里边名称包含det的文件,放在zip同目录,然后把解压后的文件夹删了。
* 这个不是工具方法。
*
* @param files
* @return
* @throws IOException
* @throws FileNotFoundException
* @throws ZipException
*/
public static void unZipRedirect(List<File> files) throws IOException, FileNotFoundException, ZipException {
for (File file : files) {
// 压缩文件路径
String packagePath = file.getAbsolutePath();
String outPath = packagePath.substring(0, packagePath.length() - 4);
String characterSet = "GBK";
try {
BufferedInputStream bi;
if (characterSet == null) {
// 默认GBK
characterSet = "GBK";
}
// 支持中文
ZipFile zf = new ZipFile(packagePath, characterSet);
Enumeration e = zf.getEntries();
while (e.hasMoreElements()) {
ZipEntry ze2 = (ZipEntry) e.nextElement();
String entryName = ze2.getName();
String path = outPath + "/" + entryName;
if (ze2.isDirectory()) {
System.out.println("正在创建解压目录 - " + entryName);
File decompressDirFile = new File(path);
if (!decompressDirFile.exists()) {
decompressDirFile.mkdirs();
}
} else {
System.out.println("正在创建解压文件 - " + entryName);
String fileDir = path.substring(0, path.lastIndexOf("/"));
File fileDirFile = new File(fileDir);
if (!fileDirFile.exists()) {
fileDirFile.mkdirs();
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath + "/" + entryName));
bi = new BufferedInputStream(zf.getInputStream(ze2));
byte[] readContent = new byte[1024];
int readCount = bi.read(readContent);
while (readCount != -1) {
bos.write(readContent, 0, readCount);
readCount = bi.read(readContent);
}
bos.close();
}
}
zf.close();
// 删除过滤所有 以__MACOSX,.DS_Store文件目录
File outFile = new File(outPath);
File[] inner1Files = outFile.listFiles();
if (inner1Files.length > 0) {
for (File inner1File : inner1Files) {
if (inner1File.getName().startsWith("__MACOSX") || inner1File.getName().startsWith(".DS_Store")) {
deleteDir(inner1File);
}
if (inner1File.isDirectory()) {
File[] inner2Files = inner1File.listFiles();
if (inner2Files.length > 0) {
for (File inner2File : inner2Files) {
if (inner2File.getName().startsWith("__MACOSX") || inner2File.getName().startsWith(".DS_Store")) {
deleteDir(inner1File);
}
}
}
}
}
}
} catch (Exception e) {
if (e.getMessage().equals("archive is not a ZIP archive")) {
System.out.println("zip压缩文件[" + file.getAbsolutePath() + "]异常,文件不能解压!" + SysUtil.lineSeparator() + Const.getStackTracker(e));
continue;
}
System.out.println("zip压缩文件[" + file.getAbsolutePath() + "]解压过程中发生异常!" + SysUtil.lineSeparator() + Const.getStackTracker(e));
continue;
} finally {
// deleteDir(new File(packagePath)); // 删除压缩包
// 获取解压后的文件全路径
List<File> filedirs = com.cenrise.mailcbc.Const.searchFile(new File(outPath), ".det.");
for (File onefile : filedirs) {
// 移动文件到zip同级目录
copy(onefile, file.getParent() + java.io.File.separator + onefile.getName());
}
// 删除生成的目录
com.cenrise.mailcbc.Const.delFolder(outPath);
}
}
}
use of java.util.zip.ZipException in project ant by apache.
the class ZipScanner method fillMapsFromArchive.
/**
* Fills the file and directory maps with resources read from the
* archive.
*
* @param src the archive to scan.
* @param encoding encoding used to encode file names inside the archive.
* @param fileEntries Map (name to resource) of non-directory
* resources found inside the archive.
* @param matchFileEntries Map (name to resource) of non-directory
* resources found inside the archive that matched all include
* patterns and didn't match any exclude patterns.
* @param dirEntries Map (name to resource) of directory
* resources found inside the archive.
* @param matchDirEntries Map (name to resource) of directory
* resources found inside the archive that matched all include
* patterns and didn't match any exclude patterns.
*/
@Override
protected void fillMapsFromArchive(Resource src, String encoding, Map<String, Resource> fileEntries, Map<String, Resource> matchFileEntries, Map<String, Resource> dirEntries, Map<String, Resource> matchDirEntries) {
File srcFile = src.asOptional(FileProvider.class).map(FileProvider::getFile).orElseThrow(() -> new BuildException("Only file provider resources are supported"));
try (ZipFile zf = new ZipFile(srcFile, encoding)) {
Enumeration<ZipEntry> e = zf.getEntries();
while (e.hasMoreElements()) {
ZipEntry entry = e.nextElement();
Resource r = new ZipResource(srcFile, encoding, entry);
String name = entry.getName();
if (entry.isDirectory()) {
name = trimSeparator(name);
dirEntries.put(name, r);
if (match(name)) {
matchDirEntries.put(name, r);
}
} else {
fileEntries.put(name, r);
if (match(name)) {
matchFileEntries.put(name, r);
}
}
}
} catch (ZipException ex) {
throw new BuildException("Problem reading " + srcFile, ex);
} catch (IOException ex) {
throw new BuildException("Problem opening " + srcFile, ex);
}
}
use of java.util.zip.ZipException in project ant by apache.
the class ZipOutputStream method handleSizesAndCrc.
/**
* Ensures the current entry's size and CRC information is set to
* the values just written, verifies it isn't too big in the
* Zip64Mode.Never case and returns whether the entry would
* require a Zip64 extra field.
*
* @param bytesWritten long
* @param crc long
* @param effectiveMode Zip64Mode
* @return boolean
* @throws ZipException if size or CRC is incorrect
*/
private boolean handleSizesAndCrc(long bytesWritten, long crc, Zip64Mode effectiveMode) throws ZipException {
if (entry.entry.getMethod() == DEFLATED) {
/* It turns out def.getBytesRead() returns wrong values if
* the size exceeds 4 GB on Java < Java7
entry.entry.setSize(def.getBytesRead());
*/
entry.entry.setSize(entry.bytesRead);
entry.entry.setCompressedSize(bytesWritten);
entry.entry.setCrc(crc);
def.reset();
} else if (raf == null) {
if (entry.entry.getCrc() != crc) {
throw new ZipException("bad CRC checksum for entry " + entry.entry.getName() + ": " + Long.toHexString(entry.entry.getCrc()) + " instead of " + Long.toHexString(crc));
}
if (entry.entry.getSize() != bytesWritten) {
throw new ZipException("bad size for entry " + entry.entry.getName() + ": " + entry.entry.getSize() + " instead of " + bytesWritten);
}
} else {
/* method is STORED and we used RandomAccessFile */
entry.entry.setSize(bytesWritten);
entry.entry.setCompressedSize(bytesWritten);
entry.entry.setCrc(crc);
}
return checkIfNeedsZip64(effectiveMode);
}
use of java.util.zip.ZipException in project ant by apache.
the class ExtraFieldUtils method parse.
/**
* Split the array into ExtraFields and populate them with the
* given data.
* @param data an array of bytes
* @param local whether data originates from the local file data
* or the central directory
* @param onUnparseableData what to do if the extra field data
* cannot be parsed.
* @return an array of ExtraFields
* @throws ZipException on error
* @since Ant 1.8.1
*/
public static ZipExtraField[] parse(byte[] data, boolean local, UnparseableExtraField onUnparseableData) throws ZipException {
List<ZipExtraField> v = new ArrayList<ZipExtraField>();
int start = 0;
LOOP: while (start <= data.length - WORD) {
ZipShort headerId = new ZipShort(data, start);
int length = (new ZipShort(data, start + 2)).getValue();
if (start + WORD + length > data.length) {
switch(onUnparseableData.getKey()) {
case UnparseableExtraField.THROW_KEY:
throw new ZipException("bad extra field starting at " + start + ". Block length of " + length + " bytes exceeds remaining data of " + (data.length - start - WORD) + " bytes.");
case UnparseableExtraField.READ_KEY:
UnparseableExtraFieldData field = new UnparseableExtraFieldData();
if (local) {
field.parseFromLocalFileData(data, start, data.length - start);
} else {
field.parseFromCentralDirectoryData(data, start, data.length - start);
}
v.add(field);
// $FALL-THROUGH$
case UnparseableExtraField.SKIP_KEY:
// available data
break LOOP;
default:
throw new ZipException("unknown UnparseableExtraField key: " + onUnparseableData.getKey());
}
}
try {
ZipExtraField ze = createExtraField(headerId);
if (local || !(ze instanceof CentralDirectoryParsingZipExtraField)) {
ze.parseFromLocalFileData(data, start + WORD, length);
} else {
((CentralDirectoryParsingZipExtraField) ze).parseFromCentralDirectoryData(data, start + WORD, length);
}
v.add(ze);
} catch (InstantiationException ie) {
throw new ZipException(ie.getMessage());
} catch (IllegalAccessException iae) {
throw new ZipException(iae.getMessage());
}
start += (length + WORD);
}
ZipExtraField[] result = new ZipExtraField[v.size()];
return v.toArray(result);
}
use of java.util.zip.ZipException in project HotswapAgent by HotswapProjects.
the class PathMatchingResourcePatternResolver method doFindPathMatchingJarResources.
/**
* Find all resources in jar files that match the given location pattern via
* the Ant-style PathMatcher.
*
* @param rootDirResource
* the root directory as Resource
* @param subPattern
* the sub pattern to match (below the root directory)
* @return a mutable Set of matching Resource instances
* @throws IOException
* in case of I/O errors
* @see java.net.JarURLConnection
* @see org.hotswap.agent.util.spring.path.springframework.util.PathMatcher
*/
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern) throws IOException {
URLConnection con = rootDirResource.getURL().openConnection();
JarFile jarFile;
String jarFileUrl;
String rootEntryPath;
boolean newJarFile = false;
if (con instanceof JarURLConnection) {
// Should usually be the case for traditional JAR files.
JarURLConnection jarCon = (JarURLConnection) con;
ResourceUtils.useCachesIfNecessary(jarCon);
jarFile = jarCon.getJarFile();
jarFileUrl = jarCon.getJarFileURL().toExternalForm();
JarEntry jarEntry = jarCon.getJarEntry();
rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
} else {
// No JarURLConnection -> need to resort to URL file parsing.
// We'll assume URLs of the format "jar:path!/entry", with the
// protocol
// being arbitrary as long as following the entry format.
// We'll also handle paths with and without leading "file:" prefix.
String urlFile = rootDirResource.getURL().getFile();
try {
int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
if (separatorIndex != -1) {
jarFileUrl = urlFile.substring(0, separatorIndex);
rootEntryPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
jarFile = getJarFile(jarFileUrl);
} else {
jarFile = new JarFile(urlFile);
jarFileUrl = urlFile;
rootEntryPath = "";
}
newJarFile = true;
} catch (ZipException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping invalid jar classpath entry [" + urlFile + "]");
}
return Collections.emptySet();
}
}
try {
if (logger.isDebugEnabled()) {
logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
}
if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
// Root entry path must end with slash to allow for proper
// matching.
// The Sun JRE does not return a slash here, but BEA JRockit
// does.
rootEntryPath = rootEntryPath + "/";
}
Set<Resource> result = new LinkedHashSet<Resource>(8);
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
JarEntry entry = entries.nextElement();
String entryPath = entry.getName();
if (entryPath.startsWith(rootEntryPath)) {
String relativePath = entryPath.substring(rootEntryPath.length());
if (getPathMatcher().match(subPattern, relativePath)) {
result.add(rootDirResource.createRelative(relativePath));
}
}
}
return result;
} finally {
// not from JarURLConnection, which might cache the file reference.
if (newJarFile) {
jarFile.close();
}
}
}
Aggregations