📄 zipper.java
字号:
//这是一个用于压缩ZIP文件的类//
import java.io.*;
import java.util.zip.*;
class Zipper {
public static boolean verbose = false;
public static int compressionLevel = Deflater.DEFAULT_COMPRESSION;
private String Name;
private ZipOutputStream zip;
private int entryNum;
public Zipper(String fileName){
Name=fileName;
entryNum=0;
}
public String getName(){
return Name;
}
public int getEntryNum(){
return entryNum;
}
public void setName(String newName){
Name=newName;
}
public int init(){
//建立并初始化一个输出流
try{
zip = new ZipOutputStream(new FileOutputStream(Name));
zip.setComment("zip file created by java");
zip.setMethod(ZipOutputStream.DEFLATED);
zip.setLevel(compressionLevel);
}
catch(Exception e){
System.out.println(e);
return 1;
}
return 0;
}
public int addFile(String fileName){
try{
File file = new File(fileName);
FileInputStream in = new FileInputStream(file);
byte[] bytes = new byte[in.available()];
in.read(bytes);
in.close();
//建立并初始化zipentry
ZipEntry entry = new ZipEntry(file.getName());
entry.setTime(file.lastModified());
// write the entry header, and the data, to the zip
zip.putNextEntry(entry);
zip.write(bytes);
// write the end-of-entry marker to the zip
zip.closeEntry();
}
catch(Exception e){
System.out.println(e);
return 1;
}
entryNum++;
return 0;
}
public int close(){
try{
zip.close();
}
catch(Exception e){
System.out.println(e);
return 1;
}
return 0;
}
public static void main( String[] args ){
boolean verbose = false;
int compressionLevel = Deflater.DEFAULT_COMPRESSION;
int argc = args.length;
int argn;
// 解析命令行参数
for (argn=0; (argn<args.length) && args[argn].charAt(0)=='-'; ++argn){
if ( args[argn].equals( "-v" ) )
verbose = true;
else if ( args[argn].equals( "-l" ) ) {
++argn;
compressionLevel = Integer.parseInt(args[argn]);
}
else{
System.out.println( "usage: Zipper [-v] [-f] [-l level] zipfile files" );
return;
}
}
if ( argc - argn < 1 ){
System.out.println( "usage: Zipper [-v] [-f] [-l level] zipfile files" );
return;
}
else try{
//余下的第一个参数是生成ZIP文件的名称
Zipper zip=new Zipper(args[argn++]);
zip.verbose=verbose;
zip.compressionLevel=compressionLevel;
zip.init();
//其余的参数是需要压缩的文件的名称
for ( ; argn < args.length; ++argn )
//将一个文件读入内存
zip.addFile(args[argn]);
zip.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -