首先判断需要解压的文件是否存在或路径是否正确,接着判断路径是否存在,若不存在则创建路径,然后判断压缩文件是否合法,最后设置文件名称编码为“gbk”即可。
免费在线教学视频分享:java教学视频
示例代码:
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相关文章教程:java开发入门
以上就是java解压zip包出现乱码的详细内容。