📄 myzip.java
字号:
package Prob_2;
import java.io.*;
import java.util.zip.*;
public class MyZip {
/**
* @param args
*/
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
File file1 = new File( args[0] );
if( file1.isDirectory() )
{ //此时是要将文件夹压缩成zip文件
File file2 = new File( args[1] );
ZipOutputStream zout = new ZipOutputStream(
new BufferedOutputStream( new FileOutputStream( file2 )));
Zip( file1, zout, "" );
zout.close();
}// end if
else if ( file1.isFile() )
{ //此时是要将zip文件解压到文件夹
Unzip( args[0], args[1] );
}// end if
System.out.println( "OK" );
}// end method main
public static void Zip( File file1, ZipOutputStream zout, String base ) //file1是目录,file2是zip文件
{
try
{
File[] fl = file1.listFiles(); //用一个数组存储文件夹中的所有文件
for (int i=0; i < fl.length; i++ )
{
String tempStr = "/";
if (base.equals(""))
{ //此时本Zip方法不被任何Zip方法调用
tempStr = "";
}// end if
if( fl[i].isFile() )
{ //若fl[i]是文件则对其进行压缩
zout.putNextEntry( new ZipEntry( base + tempStr + fl[ i ].getName() ) );
int temp;
BufferedInputStream in = new BufferedInputStream(
new FileInputStream( fl[i] ));
//写入压缩文件
while( (temp = in.read())!= -1 )
zout.write( temp );
//显示进度
System.out.println( "Compress " + fl[ i ] + " successfully!");
in.close();
}// end if
else
{ //若fl[i]是文件夹则嵌套调用Zip方法对fl[i]进行压缩
Zip( fl[i], zout, base + tempStr + fl[i].getName() );
System.out.println(fl[i]);
}// end else
}// end for
}// end try
catch(IOException e)
{
System.out.println( e );
}
//System.out.println( "This before zout.close" );
//zout.close();
}
public static void Unzip( String args0, String args1 )throws IOException
{
ZipInputStream in = new ZipInputStream( new FileInputStream( args0 ));
ZipEntry z;
File t = new File( args1 );
if(!(t.exists()))
{
t.mkdirs();
}
else
System.out.println("There is already " + t); //假如解压目标文件夹已经存在,则进行提示,但仍会继续解压
//System.out.println("Unzip" );
while( (z = in.getNextEntry()) != null )
{
try{
String name = z.getName();
name = name.replace("/", "\\"); //将ZipEntry名字中的斜杠全部替换成Windows标准的分隔符
//name中此时为压缩文件的相对路径
if (z.isDirectory())
{ //假如是文件夹则在对应的位置新建文件夹
File f = new File( args1 , name );
f.mkdirs();
}// end if
else
{ //假如是文件则在对应的位置创建并写入文件
File f = new File( args1 , name );
File parent = f.getParentFile();
//假如其父文件夹不存在则创建
if (!(parent.exists()))
parent.mkdirs();
f.createNewFile();
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream( f ));
//写入文件
int temp;
while( (temp = in.read()) != -1 )
out.write(temp);
System.out.println( "Unzip " + f + " successfully!" );
out.close();
}// end else
}// end try
catch( IOException e)
{
System.out.println( e + " aya");
}// end catch
}// end while
in.close();
}// end method Unzip
}// end class MyZip
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -