?? 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 + -