📄 compress.java
字号:
/*** 本程序在定义两个用来压缩文件和目录静态方法的同时还将说明了使用嵌套类的方法。 **/import java.io.*;import java.util.zip.*;public class Compress { /**将from文件的内容进行压缩并且将压缩结果存入to文件中*/ public static void gzipFile(String from, String to) throws IOException { //创建一个从from文件中读取信息的流 FileInputStream in = new FileInputStream(from); //创建一个将数据进行压缩并且存入to文件中的流 GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to)); //将字节从一个流复制到另一个流中 byte[] buffer = new byte[4096]; int bytes_read; while((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); //关闭这个流 in.close(); out.close(); } /**对指定的目录进行压缩,并将压缩结果存入zipfile中*/ public static void zipDirectory(String dir, String zipfile) throws IOException, IllegalArgumentException { //确定指定的目标是否为一个正常目录,并且获取其内容 File d = new File(dir); if (!d.isDirectory()) throw new IllegalArgumentException("Compress: not a directory: " + dir); String[] entries = d.list(); byte[] buffer = new byte[4096]; //为复制创建一个buffer int bytes_read; //创建一个流用来压缩数据并将其写入zipfile中 ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); //在整个目录中进行循环 for(int i = 0; i < entries.length; i++) { File f = new File(d, entries[i]); if (f.isDirectory()) continue; //不要压缩子目录 FileInputStream in = new FileInputStream(f); //读取文件的流 ZipEntry entry = new ZipEntry(f.getPath()); //创建一个ZipEntry out.putNextEntry(entry); //存贮这个entry while((bytes_read = in.read(buffer)) != -1) //复制其中的字节 out.write(buffer, 0, bytes_read); in.close(); //关闭输入流 } //当完成所有的循环后,关闭输出流 out.close(); } /** *本嵌套类是一个测试程序,用来说明上面所定义的两个静态方法的使用方法 **/ public static class Test { /** *对指定的文件或目录进行压缩 *如果没有指定目标的名称,则在文件名后附加一个.gz后缀,在目录名后附加一个.zip后缀。 **/ public static void main(String args[]) throws IOException { if ((args.length != 1)&& (args.length != 2)) { //检验参数 System.err.println("Usage: java Compress$Test <from> [<to>]"); System.exit(0); } String from = args[0], to; File f = new File(from); boolean directory = f.isDirectory(); //判断目标是一个文件还是一个目录 if (args.length == 2) to = args[1]; else { //如果目标没有被指定 if (directory) to = from + ".zip"; //附加一个.zip后缀 else to = from + ".gz"; //或者附加一个.zip后缀 } if ((new File(to)).exists()) { //确定不要覆盖现存的文件或目录 System.err.println("Compress: won't overwrite existing file: "+ to); System.exit(0); } //最后,调用上面所定义的两个静态方法中的其中之一来实现具体操作 if (directory) Compress.zipDirectory(from, to); else Compress.gzipFile(from, to); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -