java代码对于zip压缩包的解压、压缩等等操作,建议使用zip4j。相关的文章有很多,不再赘述。此处只讨论解压缩之后可能出现的中文乱码问题。
问题代码:
public static void unZip( String zipPath, String destDir ) throws Exception
{
ZipFile zipFile = new ZipFile( zipPath ) ;
zipFile.setFileNameCharset( "GBK" ) ;
zipFile.extractAll( destDir ) ;
}
这段代码正常情况下可以满足大多数压缩包的解压。但是当该压缩包中的文件夹或者文件是以UNICODE编码命名,解压以后就会出现中文乱码问题。
所以我们需要在解压之前就去判断以GBK字符集去解压是否会出现中文乱码,如果有乱码,则采用UNICODE字符集去解压。
正确代码:
public static void unZip( String zipPath, String destDir ) throws Exception
{
ZipFile zipFile = new ZipFile( zipPath ) ;
zipFile.setFileNameCharset( getEncoding( zipPath ) ) ;
zipFile.extractAll( destDir ) ;
}
@SuppressWarnings( "unchecked" )
private static String getEncoding( String path ) throws Exception
{
String encoding = "GBK" ;
ZipFile zipFile = new ZipFile( path ) ;
zipFile.setFileNameCharset( encoding ) ;
List<FileHeader> list = zipFile.getFileHeaders() ;
for( int i = 0; i < list.size(); i++ )
{
FileHeader fileHeader = list.get( i ) ;
String fileName = fileHeader.getFileName();
if( isMessyCode( fileName ) )
{
encoding = "UTF-8" ;
break ;
}
}
return encoding ;
}
private static boolean isMessyCode( String str )
{
for( int i = 0; i < str.length(); i++ )
{
char c = str.charAt( i ) ;
// 当从Unicode编码向某个字符集转换时,如果在该字符集中没有对应的编码,则得到0x3f(即问号字符?)
// 从其他字符集向Unicode编码转换时,如果这个二进制数在该字符集中没有标识任何的字符,则得到的结果是0xfffd
if( (int)c == 0xfffd )
{
// 存在乱码
return true ;
}
}
return false ;
}