`

解压zip压缩包中的指定文件(害死人的错误)

阅读更多

使用java 解压zip压缩包中的指定文件时遇到了问题。

且听我细细道来:

主要方法如下:

public static byte[] getContent2(final ZipFile zipFile, final ZipEntry zipEntry)
            throws IOException {
        InputStream inputStream = zipFile.getInputStream(zipEntry);
        int length = inputStream.available();
        byte[] bytes = new byte[length];
        inputStream.read(bytes);
        inputStream.close();
        return bytes;
    }

 测试方法如下:

@Test
	public void test_getContent() throws ZipException, IOException{
		String outPutFileStr="d:\\Temp\\a\\test.zip";
		File file=new File(outPutFileStr);
		ZipFile zipFile = new ZipFile(file);
		ZipEntry zipEntry = zipFile.getEntry("BaiduYunGuanjia_2.1.022333.exe");
		byte[]bytes=ZipUtil.getContent2(zipFile, zipEntry);
		FileUtils.writeBytesToFile(bytes, "d:\\Temp\\a\\baidu.exe");
	}

 说明:d:\\Temp\\a\\test.zip是zip压缩包,其中包含文件BaiduYunGuanjia_2.1.022333.exe。我解压的步骤是这样的:

我先通过ZipUtil.getContent2 方法获取BaiduYunGuanjia_2.1.022333.exe 的字节数组,再把该字节数组写入文件d:\\Temp\\a\\baidu.exe。

执行完之后,发现解压的文件不正确,也就是d:\\Temp\\a\\baidu.exe 与BaiduYunGuanjia_2.1.022333.exe的MD5不同。

问题到底出在哪里呢?

getContent2 方法我反复看了无数遍,也没有看出问题。

 

后来终于找到了原因:getContent2方法的第四行得到的length,但是第六行inputStream.read(bytes);读取的字节数并不是length。可以通过inputStream.read(bytes)的返回值获取真正读取的字节个数。

解决方法:

getContent2改进如下:

/**
	 * 从zip包中读取给定文件名的内容
	 * 
	 * @param zipFile
	 * @param zipEntry
	 * @return
	 * @throws IOException
	 */
	public static byte[] getContent(final ZipFile zipFile,
			final ZipEntry zipEntry) throws IOException {
		InputStream inputStream = zipFile.getInputStream(zipEntry);
		byte[] buffer = new byte[1024];
		byte[] bytes = new byte[0];
		int length;
		while ((length = (inputStream.read(buffer))) != -1) {
			byte[] readBytes = new byte[length];
			System.arraycopy(buffer, 0, readBytes, 0, length);
			bytes = SystemUtil.mergeArray(bytes, readBytes);
		}
		inputStream.close();
		return bytes;
	}

 测试方法:

@Test
	public void test_getContent() throws ZipException, IOException{
		String outPutFileStr="d:\\Temp\\a\\test.zip";
		File file=new File(outPutFileStr);
		ZipFile zipFile = new ZipFile(file);
		ZipEntry zipEntry = zipFile.getEntry("BaiduYunGuanjia_2.1.022333.exe");
		byte[]bytes=ZipUtil.getContent(zipFile, zipEntry);
		FileUtils.writeBytesToFile(bytes, "d:\\Temp\\a\\baidu.exe");
	}

 

终于ok了。

 

 

 

 

0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics