如题:源文件为一个.del文本文件,在压缩后文件末尾总是会丢失一部分数据,请高手帮我看一下代码,是哪里出错了?
public static void zip(String fileName) throws FileNotFoundException,IOException,ZipException{ //获取文件后缀,包括"." String suffix = fileName.substring(fileName.lastIndexOf(".")); String zipFileName = fileName.replace(suffix, ".zip"); File srcFile = new File(fileName); File zipFile = new File(zipFileName); if(!srcFile.exists()){ throw new FileNotFoundException("指定的源文件不存在!"); } BufferedInputStream in = null; ZipOutputStream zipOut = null; try { // 创建字节输入流对象 in = new BufferedInputStream(new FileInputStream(srcFile)); // 创建文件输出流对象 FileOutputStream f = new FileOutputStream(zipFile); CheckedOutputStream ch = new CheckedOutputStream(f, new CRC32()); // 创建ZIP数据输出流对象 zipOut = new ZipOutputStream( new BufferedOutputStream(ch, 4096)); // 创建指向压缩原始文件的入口 ZipEntry entry = new ZipEntry(srcFile.getName()); zipOut.putNextEntry(entry); // 向压缩文件中输出数据 byte[] b = new byte[4096]; int count = -1; while ((count = in.read(b)) != -1) { zipOut.write(b,0,count); } zipOut.closeEntry(); throw new IOException("error"); } catch (IOException e) { // 如果抛出异常,则删除生成的压缩文件 if(zipFile != null && zipFile.exists()){ zipOut.close();zipFile.delete(); } throw e; } finally { // 关闭创建的流对象 if(in != null) in.close(); if(zipOut != null) zipOut.close(); } }
文件压缩前后对比截图:
运行了一下lz的程序,50kb的文本文件,压缩后再解压,用差分工具比较过,跟原来的完全一致。
我用rar查看和解压文件都没有问题。有点怪 8)
恨感谢,解决我的问题^_^