public static void main(String[] args) throws IOException
{
try
{
ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(new File("E://aa.rar")));
// 创建目录级文件名
ZipEntry e = new ZipEntry("aa\\aa.jpg");
zipOutStream.putNextEntry(e);
InputStream is = new FileInputStream("E:\\aa.jpg"); // 文件流
int len = 0;
while ((len = is.read()) != -1)
zipOutStream.write(len);// 写入ZIP对象
is.close();
e = new ZipEntry("aa\\aaa.jpg");
zipOutStream.putNextEntry(e);
is = new FileInputStream("E:\\aa.jpg");
len = 0;
while ((len = is.read()) != -1)
zipOutStream.write(len);
is.close();
// 如果是上ZIP多个文件可以递归
zipOutStream.finish();
zipOutStream.flush();
zipOutStream.close();
/**
* 解压缩
*/
File file = new File("E://aa.rar");// 压缩文件
ZipFile zipFile = new ZipFile(file);// 实例化ZipFile,每一个zip压缩文件都可以表示为一个ZipFile
// 实例化一个Zip压缩文件的ZipInputStream对象,可以利用该类的getNextEntry()方法依次拿到每一个ZipEntry对象
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = null;
while ((zipEntry = zipInputStream.getNextEntry()) != null)
{
String fileName = zipEntry.getName();
File temp = new File("D:\\unpackTest\\" + fileName);
if (!temp.getParentFile().exists())
temp.getParentFile().mkdirs();
OutputStream os = new FileOutputStream(temp);
is = zipFile.getInputStream(zipEntry);
len = 0;
while ((len = is.read()) != -1)
os.write(len);
os.close();
is.close();
}
zipInputStream.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
JAVA压缩文件和解压缩文件
最新推荐文章于 2024-11-03 11:01:20 发布