ZIP压缩与解压缩
ZipEntry ZipInputStream ZipOutputStream
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;
import java. util. zip. ZipOutputStream;
public class zip {
private static void xxx ( ) {
File file = new File ( "E:\\你的盘里的文件路径" ) ;
File target = new File ( "E:\\name.zip" ) ;
try (
FileOutputStream fileOutputStream = new FileOutputStream ( target) ;
ZipOutputStream zipOutputStream = new ZipOutputStream ( fileOutputStream) ) {
System. out. println ( "压缩中..." ) ;
if ( file. isDirectory ( ) ) {
for ( File file1 : file. listFiles ( ) ) {
zip ( zipOutputStream, file1, "" ) ;
}
} else {
zip ( zipOutputStream, file, "" ) ;
}
System. out. println ( "压缩成功." ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
private static void zip ( ZipOutputStream zipOutputStream, File file, String base) {
if ( file. isDirectory ( ) ) {
for ( File file1 : file. listFiles ( ) ) {
zip ( zipOutputStream, file1, base + file1. getName ( ) + File. separator) ;
}
} else {
try {
zipOutputStream. putNextEntry ( new ZipEntry ( base) ) ;
int count = - 1 ;
byte [ ] bytes = new byte [ 1024 ] ;
FileInputStream fileInputStream = new FileInputStream ( file) ;
while ( ( count = fileInputStream. read ( bytes) ) != - 1 ) {
zipOutputStream. write ( bytes) ;
zipOutputStream. flush ( ) ;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
private static void deprogress ( ) {
File file = new File ( "E:\\name.zip" ) ;
File file1 = new File ( "E:\\解压" ) ;
byte [ ] bytes = new byte [ 1024 ] ;
ZipEntry zipEntry = null;
try (
FileInputStream fileInputStream = new FileInputStream ( file) ;
ZipInputStream zipInputStream = new ZipInputStream ( fileInputStream) ) {
while ( true ) {
zipEntry = zipInputStream. getNextEntry ( ) ;
if ( zipEntry == null) { break ; }
if ( zipEntry. isDirectory ( ) ) { continue ; }
File f = new File ( file1, zipEntry. getName ( ) ) ;
if ( ! f. getParentFile ( ) . exists ( ) ) {
f. getParentFile ( ) . mkdirs ( ) ;
}
int count = - 1 ;
FileOutputStream fileOutputStream = new FileOutputStream ( f) ;
while ( ( count = zipInputStream. read ( bytes) ) != - 1 ) {
fileOutputStream. write ( bytes, 0 , count) ;
}
zipInputStream. closeEntry ( ) ;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
public static void main ( String[ ] args) {
xxx ( ) ;
System. out. println ( "解压中..." ) ;
deprogress ( ) ;
System. out. println ( "解压完成" ) ;
}
}