java压缩流的用法_Java对压缩包的操作(解压缩)

425115faf7b0

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();

}

if (inputStream!=null){

inputStream.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

2.单文件解压

/**

* @author Surpass

* @Package com.hkrt.demo.zip

* @Description: 压缩包解压

* @date 2020/10/16 10:50

*/

public class SingleZipUnpackThe {

private static InputStream inputStream;

private static ZipInputStream bi;

private static OutputStream fileOutputStream;

private static String zipPath = "C:\\Users\\Surpass\\Desktop\\Bypass_1.14.2\\Bypass\\使用须知.zip";

//方法二

public static void main(String[] args) {

try {

//对中文名字进行了处理

ZipFile zipFile = new ZipFile(zipPath, Charset.forName("GBK"));

String zipFileParentPath = zipFile.getName().substring(0,zipFile.getName().lastIndexOf("\\"));

System.out.println(zipFileParentPath);

//获得压缩包内文件

Enumeration extends ZipEntry> entries = zipFile.entries();

while (entries.hasMoreElements()) {

ZipEntry zipEntry = entries.nextElement();

//输出文件流 压缩包路径+文件

fileOutputStream = new FileOutputStream(zipFileParentPath+"\\" + zipEntry.getName());

//写文件

byte[] bytes = new byte[1024];

int len = 0;

while ((len = bi.read(bytes))!=-1){

fileOutputStream.write(bytes,0,len);

}

}

} catch (Exception e) {

e.printStackTrace();

}finally {

try {

if (bi!=null){

bi.closeEntry();

bi.close();

}

if (fileOutputStream!=null){

fileOutputStream.close();

}

if (inputStream!=null){

inputStream.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

3.多文件压缩(保留原有结构)

/**

* @author Surpass

* @Package com.hkrt.demo.zip

* @Description: 多文件根据目录结构压缩

* @date 2020/10/17 10:13

*/

public class MultipleFilesCompression {

private static InputStream inputStream;

private static ZipOutputStream zipOutputStream;

private static OutputStream outputStream;

private static String filePath = "C:\\Users\\Surpass\\Desktop\\Bypass_1.14.25";

public static void main(String[] args) {

try {

//需要压缩的文件夹

File file = new File(filePath);

String dirName = file.getName();

String fileParentPath = file.getParent();

//需要生成的压缩包名称和生成路径

outputStream = new FileOutputStream(fileParentPath+"\\"+dirName+".zip");

zipOutputStream = new ZipOutputStream(outputStream);

//获取目录结构

Map map = new HashMap<>();

map = getFile(file, map);

//通过key遍历map

Set keySet = map.keySet();

Iterator iterator = keySet.iterator();

while (iterator.hasNext()){

//key(当是空文件夹的时候key为目录,当文件夹有文件的时候key为文件名)

String fileName = iterator.next();

//value(当是空文件夹的时候value为"",当文件夹有文件的时候value为目录)

String path = map.get(fileName);

if (path.equals("")){

//空文件夹

//这里获取从压缩包开始的路径 \Bypass\Logs>>>>>>2020-09-12.txt \Bypass\Music

String[] basePath = fileName.split(dirName);

String parent = basePath[1];

//压入压缩包流文件的存放路径 \Bypass\Music

zipOutputStream.putNextEntry(new ZipEntry(parent+"/"));

}else {

//正常文件

//文件转输入流

inputStream = new FileInputStream(path+"\\"+fileName);

//这里获取从压缩包开始的路径 \Bypass\Logs>>>>>>2020-09-12.txt \Bypass>>>>>>使用须知.txt

String[] basePath = path.split(dirName);

String parent = basePath[1];

zipOutputStream.putNextEntry(new ZipEntry(parent +"\\"+fileName));

}

//写文件

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();

}

if (inputStream!=null){

inputStream.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* @Description: 使用递归的方式向map中存入目录结构

* @param file, 需要压缩的文件

* map 存放目录结构

* @return java.util.Map

* @throws

* @author Surpass

* @date 2020/10/17 11:26

*/

private static Map getFile(File file,Map map){

File[] files = file.listFiles();

//如果是空文件夹的时候使用路径作为key

if (files.length==0){

map.put(file.getAbsolutePath(),"");

}

for (File file1 : files) {

if (file1.isDirectory()){

//递归

getFile(file1,map);

}

if (file1.isFile()){

//文件作为key,路径作为value

map.put(file1.getName(),file1.getParent());

}

}

return map;

}

}

4.多文件解压(保留原有结构)

/**

* @author Surpass

* @Package com.hkrt.demo.zip

* @Description: 压缩包解压保持原有的目录

* @date 2020/10/17 11:39

*/

public class MultipleFilesUnpackThe {

private static OutputStream outputStream;

private static InputStream inputStream;

private static ZipInputStream bi;

private static String ZipPath = "C:\\Users\\Surpass\\Desktop\\Bypass.zip";

public static void main(String[] args) {

try {

//对中文名字进行了处理

ZipFile zipFile = new ZipFile(ZipPath, Charset.forName("GBK"));

//压缩包的名字,不包含后缀 .zip

String zipName = zipFile.getName().substring(0, zipFile.getName().indexOf("."));

//压缩包所在的路径

String zipFileParentPath = zipFile.getName().substring(0,zipFile.getName().lastIndexOf("\\"));

Enumeration extends ZipEntry> entries = zipFile.entries();

while (entries.hasMoreElements()) {

ZipEntry entry = entries.nextElement();

if (entry.isDirectory()) {

//空文件夹,直接创建 压缩包路径+压缩包名字+空文件夹路径

File file = new File(zipFileParentPath+"\\"+zipName+"\\"+entry);

file.mkdirs();

}else {

//获取文件在压缩包内的路径

String entryPath = entry.getName().substring(0,entry.getName().lastIndexOf("\\"));

//为存放的路径创建文件夹

File file = new File(zipFileParentPath+"\\"+zipName+"\\"+entryPath);

if (!file.exists()) {

file.mkdirs();

}

outputStream = new FileOutputStream(zipFileParentPath+"\\"+zipName+"\\"+ entry.getName());

}

//写文件

byte[] bytes = new byte[1024];

int len = 0;

while ((len = bi.read(bytes))!=-1){

outputStream.write(bytes,0,len);

}

}

} catch (Exception e) {

e.printStackTrace();

}finally {

try {

if (bi!=null){

bi.closeEntry();

bi.close();

}

if (inputStream!=null){

inputStream.close();

}

if (outputStream!=null){

outputStream.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

总结

看网上的例子说有什么jar能简单一下,博主这里没有尝试去看,既然这样写了,也算是一个不错的练习。当然,博主道行较浅,代码不规范是一方面,如果有什么不足之处,还望各位大牛批评指正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java中有两种常用的压缩: java.util.zip.GZIPOutputStream和java.util.zip.ZipOutputStream. 它们都是继承自 java.io.OutputStream, 可以将一个字节转换为压缩写入文件. 例如,下面是一个将文本文件压缩成 gzip 格式的例子: ``` import java.io.*; import java.util.zip.*; public class GzipExample { public static void main(String[] args) throws IOException { String filePath = "example.txt"; String gzipFilePath = "example.txt.gz"; try (InputStream inputStream = new FileInputStream(filePath); OutputStream outputStream = new GZIPOutputStream(new FileOutputStream(gzipFilePath))) { byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } } } } ``` 上面的代码将example.txt文件转换成了example.txt.gz文件 需要注意,在读取一个压缩时,需要使用相应的解压缩,如GZIPInputStream和ZipInputStream. ### 回答2: Java中的压缩用于压缩数据,而字节则用于处理原始的字节数据。因此,将Java压缩转换为字节可以在压缩/解压缩数据时使用原始的字节数据。 在Java中,可以使用两种压缩ZipOutputStream和GZIPOutputStream。ZipOutputStream用于创建压缩包,而GZIPOutputStream用于创建.gz格式的压缩文件。 要将压缩转换为字节,可以使用ByteArrayOutputStream类。这个类是一个输出,它可以将压缩的输出保存到内存中的字节数组中。这种转换的过程如下: 1. 创建一个压缩对象,如ZipOutputStream或GZIPOutputStream。 2. 创建一个ByteArrayOutputStream对象,作为压缩的输出。 3. 将ByteArrayOutputStream对象传递给压缩的构造方法,以便将输出保存到字节数组中。 4. 使用压缩进行压缩操作。 5. 完成压缩后,可以使用toByteArray()方法从ByteArrayOutputStream对象中获取压缩后的字节数组。 要注意的是,使用字节数组保存压缩数据可能会导致内存占用较多,特别是对于大型文件或数据。因此,在使用压缩转换为字节时,需要考虑内存的使用情况,并适时释放或清空字节。 总之,Java压缩可以通过使用ByteArrayOutputStream来转换为字节,以处理原始的字节数据。这种转换可以方便地在压缩/解压缩数据时使用字节。 ### 回答3: Java中,压缩是用来将数据进行压缩的工具,而字节则是用来处理以字节为单位的数据的工具。在某些情况下,我们可能需要将压缩转换为字节来进行进一步的处理或传输。 首先,我们可以使用Java中的压缩(例如GZIPOutputStream或DeflaterOutputStream)将数据进行压缩。这些压缩可以接受字节作为输入,并将其压缩压缩(字节)。 然后,我们可以使用Java中的字节(例如ByteArrayInputStream)来读取压缩并将其转换为字节。这将允许我们以字节为单位处理压缩后的数据。 以下是一个简单的示例,演示了如何将压缩转换为字节: ```java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.zip.GZIPOutputStream; public class CompressionExample { public static void main(String[] args) { try { // 创建一个字节数组输出,用于保存压缩后的数据 ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); // 创建一个GZIPOutputStream用于将数据压缩压缩(字节) GZIPOutputStream gzipOutput = new GZIPOutputStream(byteOutput); // 写入需要压缩的数据 gzipOutput.write("Hello, World!".getBytes()); gzipOutput.close(); // 从字节数组输出中获取压缩后的数据 byte[] compressedData = byteOutput.toByteArray(); // 使用ByteArrayInputStream将压缩转换为字节 ByteArrayInputStream byteInput = new ByteArrayInputStream(compressedData); // 读取字节中的数据 int byteRead; while ((byteRead = byteInput.read()) != -1) { // 处理每个字节的数据 // 例如,可以将每个字节写入文件或进行其他操作 System.out.print((char) byteRead); } } catch (Exception e) { e.printStackTrace(); } } } ``` 这是一个简单的示例,演示了如何将压缩转换为字节以及如何处理字节中的数据。在实际应用中,你可能需要根据具体的需求进行更详细的处理和操作

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值