以压缩Zip文件为例。主要是通过ZipOutputStream类实现。
import java.io.*; import java.util.*; import java.text.*; import java.util.zip.*; //压缩一个文件 //压缩一个文件夹 public class Hello { public static void main(String[] args)throws Exception { final int BUFFER_LENGTH = 1024*1024; byte[] buffer = new byte[BUFFER_LENGTH]; File sourceFile = new File("D:\\AsmTools"); File zipFile = new File("d:\\"+getFileName(sourceFile.getName())+".zip"); InputStream is = null; ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); int len = 0; File[] files = sourceFile.listFiles(); for(File file : files) { is = new FileInputStream(file); zipOut.putNextEntry(new ZipEntry(file.getName())); while((len= is.read(buffer,0,BUFFER_LENGTH))>0) { zipOut.write(buffer,0,len); } is.close(); } zipOut.close(); } public static String getFileName(String fileName) { String retVal; int lastIndex = fileName.lastIndexOf("."); if(lastIndex < 0) retVal = fileName; else retVal = fileName.substring(0,lastIndex); return retVal; } }
解压缩主要使用ZipFile类和ZipOutputStream类。
ZipOutputStream 获取压缩文件中的每个ZipEntry,然后ZipFile通过ZipEntry拿到输入流。
import java.io.*; import java.util.*; import java.text.*; import java.util.zip.*; //压缩一个文件 //压缩一个文件夹 public class Hello { public static void main(String[] args)throws Exception { final int BUFFER_LENGTH = 1024*1024; File sourceZipFile = new File("d:\\AsmTools.zip"); File unzippedFolder = new File("d:\\"+getFileName(sourceZipFile.getName())); ZipInputStream zipInput = new ZipInputStream(new FileInputStream(sourceZipFile)); ZipFile zipFile = new ZipFile(sourceZipFile); ZipEntry tempZipEntry = null; InputStream is = null; OutputStream os = null; byte[] buffer = new byte[BUFFER_LENGTH]; int bytesReaded = 0; if(!unzippedFolder.exists()) { unzippedFolder.mkdir(); } while((tempZipEntry = zipInput.getNextEntry()) != null) { is = zipFile.getInputStream(tempZipEntry); os = new FileOutputStream("d:\\" + unzippedFolder.getName()+"\\"+tempZipEntry.getName()); System.out.println("正在解压:" + tempZipEntry.getName()); while((bytesReaded = is.read(buffer,0,BUFFER_LENGTH))>0) { os.write(buffer,0,bytesReaded); } is.close(); os.close(); } zipInput.close(); } public static String getFileName(String fileName) { String retVal; int lastIndex = fileName.lastIndexOf("."); if(lastIndex < 0) retVal = fileName; else retVal = fileName.substring(0,lastIndex); return retVal; } }
时间: 2024-10-21 15:01:58