怎么解决java解压zip包出现乱码?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
解决思路:
首先判断需要解压的文件是否存在或路径是否正确,接着判断路径是否存在,若不存在则创建路径,然后判断压缩文件是否合法,最后设置文件名称编码为“GBK”即可。
示例代码:
package com.yunfei.fts;
import java.io.File;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
public class ZipUtil {
/**
* todo zip解压缩
* @param source 压缩文件全路径
* @param target 要解压路径
* @param targetName 解压文件夹名称
*/
public static void unzip (String source,String target,String targetName) throws Exception{
try {
File file = new File(source);
if(!file.exists() || file.isDirectory()){
throw new Exception("将要解压文件不存在或路径填写不正确!");
}
file = new File(target+File.separator+targetName);
if(!file.exists()){
file.mkdirs();
System.out.println("路劲不存在,创建路径");
}
ZipFile zipfile = new ZipFile(source);
if (!zipfile.isValidZipFile()) {
throw new Exception("压缩文件不合法,可能被损坏.");
}
zipfile.setFileNameCharset("GBK");
zipfile.extractAll(target+File.separator+targetName);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/**
* todo 生成zip压缩
* @param source 要压缩文件全路径
* @param target 压缩文件存放路径
* @param targetName 解压文件名称
*/
public static void zip (String source,String target,String targetName) throws Exception{
try {
File file = new File(target);
if(!file.exists()){
file.mkdirs();
System.out.println("解压存储路劲不存在,创建路径");
}
file = new File(source);
if(!file.exists()){
throw new Exception("将要解压文件不存在或路径填写不正确!");
}
ZipFile zipfile = new ZipFile(target+File.separator+targetName);
zipfile.setFileNameCharset("GBK");
ZipParameters params = new ZipParameters();
params.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式
params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 压缩级别
//zipfile.cr
if(file.isFile()){
zipfile.addFile(file, params);
}else{
zipfile.addFolder(source, params);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public static void main(String[] args) {
try {
unzip("d:\\home.zip","e:\\","test");
zip("D:\\home","e:\\","test.zip");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
看完上述内容,你们掌握解决java解压zip包出现乱码的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。