Java压缩组件出现文件名乱码如何解决

  介绍

这篇文章给大家介绍Java压缩组件出现文件名乱码如何解决,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

最近发现Java原生的Zip压缩组件在压缩过程中,不支持文件名的中文编码,会在压缩过程中把中文文件名变成乱码.Apache的蚂蚁包中的压缩组件修复了这个问题,如果你在使用压缩功能时需要支持中文文件名,建议你直接使用Apache的压缩组件来实现这个功能。

具体使用方法:

1。在你的pom文件中增加对Apache的蚂蚁工具包的依赖关系:

 & lt; dependency>
  & lt; groupId> org.apache.ant
  & lt; artifactId> ant
  & lt; version> 1.9.3
  & lt;/dependency> 

并在头部引用用到的类:

进口org.apache.tools.zip.ZipEntry;
  进口org.apache.tools.zip.ZipFile;
  进口org.apache.tools.zip.ZipOutputStream; 

2。压缩的方法实现,大家注意,本组件支持设置编码(,(“GBK")被方法),解决了中文编码的问题:

公共静态孔隙压缩(字符串,字符串dstPath)抛出IOException {
  文件srcFile=新文件(srcPath);
  文件dstFile=新文件(dstPath);
  如果(! srcFile.exists ()) {
  把新FileNotFoundException (srcPath +“不exists");
  }
  
  FileOutputStream=零;
  ZipOutputStream zipOut=零;
  尝试{=新FileOutputStream (dstFile);
  zipOut=new ZipOutputStream(新BufferedOutputStream ());
  zipOut.setEncoding (“GBK");
  字符串baseDir=?“;
  压缩(srcFile zipOut baseDir);
  }
  抓住(Throwable特异){
  把新RuntimeException (ex);
  }
  最后{
  如果(零!=zipOut) {
  zipOut.close ();=零;
  }
  
  如果(零!=){
  out.close ();
  }
  }
  }
  
  
  私有静态孔隙压缩(文件文件,ZipOutputStream zipOut,字符串baseDir)抛出IOException {
  如果(file.isDirectory ()) {
  compressDirectory(文件、zipOut baseDir);
  其他}{
  compressFile(文件、zipOut baseDir);
  }
  }/* *压缩一个目录*/私有静态孔隙compressDirectory(文件dir, ZipOutputStream zipOut,字符串baseDir)抛出IOException {
  文件[]文件=dir.listFiles ();
  for (int i=0;我& lt;files.length;我+ +){
  (压缩文件[我]、zipOut baseDir + dir.getName () +“/?;
  }
  }/* *压缩一个文件*/私有静态孔隙compressFile(文件文件,ZipOutputStream zipOut,字符串baseDir)抛出IOException {
  如果(! file.exists ()) {
  返回;
  }
  
  BufferedInputStream bis=零;
  尝试{
  bis=new BufferedInputStream(新FileInputStream(文件);=new ZipEntry ZipEntry条目(baseDir + file.getName ());
  zipOut.putNextEntry(入口);
  int数;
  字节数据[]=new字节(缓冲);
  在((count=清算银行。阅读(0,数据缓冲区)!=1){
  zipOut。写(数据、0数);
  }
  
  最后}{
  如果(零!=bis) {
  bis.close ();
  }
  }
  }

3。解压缩的实现:

公共静态真空减压(字符串,字符串dstPath)抛出IOException {
  文件pathFile=新文件(dstPath);
  如果(! pathFile.exists ()) {
  pathFile.mkdirs ();
  }
  ZipFile邮政=new ZipFile (ZipFile);
  (枚举项=zip.getEntries (); entries.hasMoreElements ();) {
  ZipEntry入口=(ZipEntry) entries.nextElement ();
  字符串zipEntryName=entry.getName ();
  InputStream=零;
  OutputStream=零;
  尝试{
  在=zip.getInputStream(入口);
  字符串outPath=(dstPath +“/? zipEntryName) .replaceAll (“\ \ *”,“/?;;//判断路径是否存在,不存在则创建文件路径
  文件文件=新文件(outPath。substring (0, outPath.lastIndexOf (& # 39;/& # 39;)));
  如果(! file.exists ()) {
  file.mkdirs ();
  }//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
  如果(新文件(outPath) .isDirectory ()) {
  继续;
  }=新FileOutputStream (outPath);
  byte[]来=新字节[1024];
  int len;
  在((len=in.read(来)在0){
  out.write(来,0,len);
  }
  }
  最后{
  如果(零!=){
  in.close ();
  }
  
  如果(零!=){
  out.close ();
  }
  }
  }
  }

关于Java压缩组件出现文件名乱码如何解决就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看的到。

Java压缩组件出现文件名乱码如何解决