image
前言
如何用Java对文件进行加压和压缩
上篇文章说了项目中对根据URL提供的HTML代码中的文件URL进行下载,将下载后的文件存放在服务器上,但是文件下载下来都是ZIP压缩包。那么这篇就来看Java如何多文件进行解压缩操作。
一、正文
这里没有使用其他的jar包,利用Java中的IO流直接对文件进行操作,为了方便将文件放入桌面,路径为:C:\Users\Surpass\Desktop。
二、使用步骤
博主尽量在代码中添加明确的注释,以便于理解,所以直接贴代码了。
1.单文件压缩
/**
* @author Surpass
* @Package com.hkrt.demo.zip
* @Description: 单文件压缩
* @date 2020/10/16 10:51
*/
public class SingleZipCompression {
private static InputStream inputStream;
private static ZipOutputStream zipOutputStream;
private static OutputStream outputStream;
private static String filePath = "C:\\Users\\Surpass\\Desktop\\Linux就该这么学 高清晰PDF.pdf";
public static void main(String[] args) {
try {
//文件输入流
File file = new File(filePath);
inputStream = new FileInputStream(file);
//压缩输出路径的流 压缩文件路径+压缩文件名前缀(Linux就该这么学 高清晰PDF)+.zip
outputStream = new FileOutputStream(file.getParent()+"\\"+file.getName().substring(0,file.getName().lastIndexOf("."))+".zip");
zipOutputStream = new ZipOutputStream(outputStream);
//压缩包内文件的名字 Linux就该这么学 高清晰PDF.pdf
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
//输出文件
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes))!=-1){
zipOutputStream.write(bytes,0,len);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (zipOutputStream!=null){
zipOutputStream.closeEntry();
zipOutputStream.close();
}
if (outputStream!=null){
outputStream.close();
}