JAVA解压压缩包后的中文乱码问题

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 ;
}
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值