Java 中的文件压缩和解压缩
读取特定文件的数据并压缩一些文件到zip压缩包中,是 Java 中封装的过程。Java 环境中提供了两个压缩和解压缩类,它们提供数据deflate压缩格式。它们是:
DeflaterOutputStream 类 - 用于将文件压缩成deflate格式,例如 GZIPOutputStream。
InflaterInputStream 类 - 用于以deflate格式解压缩文件,例如 GZIPInputStream。
示例
这是一个关于如何在 Java 中将文件压缩成 Zip 文件的示例:
try { File file = new File(filePath); String zipFileName = file.getName().concat(".zip"); FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); zos.putNextEntry(new ZipEntry(file.getName())); byte[] bytes = Files.readAllBytes(Paths.get(filePath)); zos.write(bytes, 0, bytes.length); zos.closeEntry(); zos.close(); } catch (FileNotFoundException ex) { System.err.format("The file %s does not exist", filePath); } catch (IOException ex) { System.err.println("I/O error: " + ex); }
在 Java 中执行文件压缩和解压缩的算法
在这个可能的算法中,我们将向您展示如何使用 Java 环境执行压缩和解压缩过程以获得所需结果。
步骤 1 - 开始该过程。
步骤 2 - 声明并导入 Java 包以执行压缩和解压缩过程。
步骤 3 - 声明一个公共类。
步骤 4 - 声明一个字符串参数。
步骤 5 - 分配原始文件,这可能会抛出异常。
步骤 6 - 声明一个 FileInputStream 以执行读取数据操作。
步骤 7 - 分配第二个压缩文件。
步骤 8 - 声明一个 FileOutputStream 以执行读取数据操作。
步骤 9 - 从 FileInputStream 读取数据。
步骤 10 - 将数据写入 DeflaterOutputStream。
步骤 11 - 获取压缩和解压缩文件作为输出。
步骤 12 - 关闭文件。
步骤 13 - 获取返回值。
步骤 14 - 终止该过程。
Java 中文件压缩和解压缩的语法
public class CompressingFiles { public static void main(String args[]) throws IOException { String inputPath = "Declare The File Path Input"; FileInputStream inputStream = new FileInputStream(inputPath); String outputPath = "Declare The File Path Output"; FileOutputStream outputStream = new FileOutputStream(outputPath); DeflaterOutputStream compresser = new DeflaterOutputStream(outputStream); int contents; while ((contents=inputStream.read())!=-1){ compresser.write(contents); } compresser.close(); System.out.println("File compressed Today....."); } public class DeCompressingFiles { public static void main(String args[]) throws IOException { StringinputPath ="Declare The File Path Input"; FileInputStream inputStream = new FileInputStream(inputPath); String outputpath = "Declare The File Path Output"; FileOutputStream outputStream = new FileOutputStream(outputpath); InflaterInputStream decompresser = new InflaterInputStream(inputStream); int contents; while ((contents=decompresser.read())!=-1){ outputStream.write(contents); } outputStream.close(); decompresser.close(); System.out.println("File un-compressed today"); } }
在上述可能的语法中,我们尝试向您展示如何声明和创建压缩和解压缩类,并最终获得 zip 文件。通过使用这些特定的语法,我们正在朝着可能的 Java 方法前进,以有效地解决问题陈述。
遵循的方法
方法 1 - 使用 DeflaterOutputStream 压缩文件并使用 InflaterInputStream 解压缩文件的 Java 程序
方法 2 - Java 程序在单个文件和多个文件上运行压缩和解压缩操作
方法 1:使用 DeflaterOutputStream 压缩文件并使用 InflaterInputStream 解压缩文件
使用 DeflaterOutputStream 方法压缩文件
在这种可能的方法中,我们将应用 DeflaterOutputStream,它能够将文件压缩成 deflate 格式。
DeflaterOutputStream dos=new DeflaterOutputStream(fos); InflaterInputStream iis=new InflaterInputStream(fis)
示例
//Java program to crompress some files by using java.util.zip.DeflaterOutputStream import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; public class zipoperation{ public static void main(String[] args) throws IOException { FileInputStream fis=new FileInputStream("File 1 ARBRDD"); FileOutputStream fos=new FileOutputStream("File 2 ARBRDD"); DeflaterOutputStream dos=new DeflaterOutputStream(fos); int data; while ((data=fis.read())!=-1){ dos.write(data); } fis.close(); dos.close(); } }
Exception in thread "main" java.io.FileNotFoundException: File 1 ARBRDD (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112) at zipoperation.main(zipoperation.java:10)
使用 InflaterInputStream 方法解压缩文件
在这种可能的方法中,我们将应用 InflaterInputStream,它能够将文件解压缩成 deflate 格式。
示例
//Java program to crompress some files by using java.util.zip.InflaterInputStream import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.InflaterInputStream; public class unzipARBRDD{ public static void main(String[] args) throws IOException { FileInputStream fis=new FileInputStream("File 2 ARBRDD"); FileOutputStream fos=new FileOutputStream("File 3 ARBRDD"); InflaterInputStream iis=new InflaterInputStream(fis); int data; while((data=iis.read())!=-1){ fos.write(data); } fos.close(); iis.close(); } }
输出
Exception in thread "main" java.io.FileNotFoundException: File 2 ARBRDD (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112) at unzipARBRDD.main(unzipARBRDD.java:9)
免责声明 - 在上面提到的每个 Java 代码中,用户在运行此代码时都会遇到异常。提到的异常仅针对文件路径,这是每个用户及其系统的唯一语句。
方法 2:在单个文件和多个文件上运行压缩和解压缩操作
使用各种流方法
在这种可能的方法中,我们将应用 Java 环境中存在的输入输出流,应用于多个文件以及目录文件。运行这些 Java 方法后,我们将以 Zip 文件的形式获得所需的输出。
FileInputStream fin=new FileInputStream("File Name.java"); FileOutputStream fout=new FileOutputStream("Compressed File.txt");
示例 1
//Java Program to compress a single file with input output stream import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZippingAFileExample { public static void main(String[] args) throws IOException { String sourceFile = "src-file.txt"; FileOutputStream fos = new FileOutputStream("compressed.zip"); System.out.println("File compression started."); ZipOutputStream zipOut = new ZipOutputStream(fos); File fileToZip = new File(sourceFile); FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } zipOut.close(); fis.close(); fos.close(); System.out.println("Done"); } }
输出
File compression started. Exception in thread "main" java.io.FileNotFoundException: src-file.txt (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at ZippingAFileExample.main(ZippingAFileExample.java:15)
示例 2
//Java Program to compress a multiple files at a time in Single Program import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ARBRDD{ public static void main(String[] args) throws IOException { List<String> srcFiles = Arrays.asList("file-1.txt", "file-2.txt", "file- 3.txt"); FileOutputStream fos = new FileOutputStream("multifilesCompressed.zip"); System.out.println("Zipping started."); ZipOutputStream zipOut = new ZipOutputStream(fos); for (String srcFile : srcFiles) { File fileToZip = new File(srcFile); FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } fis.close(); } zipOut.close(); fos.close(); System.out.println("Done"); } }
输出
Zipping started. Exception in thread "main" java.io.FileNotFoundException: file-1.txt (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at ARBRDD.main(ARBRDD.java:18)
示例 3
//Java Program to compress a directory at a time import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ARBRDD { public static void main(String[] args) throws IOException { String sourceFile = "src"; FileOutputStream fos = new FileOutputStream("DirSrcCompressed.zip"); ZipOutputStream zipOut = new ZipOutputStream(fos); File fileToZip = new File(sourceFile); zipFile(fileToZip, fileToZip.getName(), zipOut); zipOut.close(); fos.close(); } private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException { if (fileToZip.isHidden()) { return; } if (fileToZip.isDirectory()) { if (fileName.endsWith("/")) { zipOut.putNextEntry(new ZipEntry(fileName)); zipOut.closeEntry(); } else { zipOut.putNextEntry(new ZipEntry(fileName + "/")); zipOut.closeEntry(); } File[] children = fileToZip.listFiles(); for (File childFile : children) { zipFile(childFile, fileName + "/" + childFile.getName(), zipOut); } return; } FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileName); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } fis.close(); } }
输出
Exception in thread "main" java.io.FileNotFoundException: src (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at ARBRDD.zipFile(ARBRDD.java:37) at ARBRDD.main(ARBRDD.java:14)
示例 4
//Java Program to unzip a compressed .zip file import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class UnzipFileARBRDD { public static void main(String[] args) { String zipFilePath = "multifilesCompressed.zip"; unzip(zipFilePath); } private static void unzip(String zipFilePath) { File dir = new File("."); if (!dir.exists()) dir.mkdirs(); FileInputStream fis; byte[] buffer = new byte[1024]; try { fis = new FileInputStream(zipFilePath); ZipInputStream zis = new ZipInputStream(fis); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName(); File newFile = new File("." + File.separator + fileName); System.out.println("Unzipping to " + newFile.getAbsolutePath()); new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); zis.closeEntry(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
输出
java.io.FileNotFoundException: multifilesCompressed.zip (No such file or directory) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112) at UnzipFileARBRDD.unzip(UnzipFileARBRDD.java:20) at UnzipFileARBRDD.main(UnzipFileARBRDD.java:11)
免责声明 - 在上面提到的每个 Java 代码中,用户在运行此代码时都会遇到异常。提到的异常仅针对文件路径,这是每个用户及其系统的唯一语句。
结论
在 Java 环境中,引入了 DeflaterOutputStream 和 InflaterInputStream 类来压缩和解压缩文件内容,它们提供了可用于将文件内容压缩到 ZIP 文件中的有用方法。在本文中,我们学习了如何使用 Java 函数执行压缩操作。通过上面提到的语法和 Java 方法以及算法,我们尝试以有效的方式解决问题陈述。
另请参阅: Java 面试问题及答案