JAVA代码导出文件设置编码_如何使用UTF-8编码打开java程序生成的zip文件

我们的产品有一个导出功能,它使用ZipOutputStream压缩目录;但是,当您尝试压缩包含具有中文或日文字符的文件名的目录时,导出将无法正常工作.由于某种原因,压缩文件中的新文件的命名方式不同.以下是我们的压缩代码示例:

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));

out.setEncoding("UTF-8");

//program to add directory to zip

//program add/create file to zip

out.close();

我的导入算法也是用Java构建的,即使文件/目录名中包含中文/日文字符,也可以正确导入压缩文件.

Zipfile zipfile = new ZipFile(zipPath, "UTF-8");

Enumeration e = zipFile.getEntries();

while (e.hasMoreElements()) {

entry = (ZipEntry) e.nextElement();

String name = entry.getName();

....

zip软件的程序是否在解压缩UTF-8编码文件时遇到问题,或者是否有一些特殊需要创建一个zip文件,现有软件可以使用utf-8编码轻松使用?

我写了一个示例程序:

package ZipFile;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import org.apache.tools.zip.ZipEntry;

import org.apache.tools.zip.ZipOutputStream;

public class ZipFolder{

public static void main(String[] a) throws Exception

{

String srcFolder = "D:/9.4_work/openscript_repo/中文124.All/中文";

String destZipFile = "D:/Eclipse_Projects/OpenScriptDebuggingProject/src/ZipFile/demo.zip";

zipFolder(srcFolder, destZipFile);

}

static public void zipFolder(String srcFolder, String destZipFile) throws Exception

{

ZipOutputStream zip = null;

FileOutputStream fileWriter = null;

fileWriter = new FileOutputStream(destZipFile);

zip = new ZipOutputStream(fileWriter);

zip.setEncoding("UTF-8");

// using GBK encoding, the chinese name can be correctly displayed when unzip

// zip.setEncoding("GBK");

addFolderToZip("", srcFolder, zip);

zip.flush();

zip.close();

}

static private void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws Exception

{

File folder = new File(srcFile);

if (folder.isDirectory()) {

addFolderToZip(path, srcFile, zip);

}

else {

byte[] buf = new byte[1024];

int len;

FileInputStream in = new FileInputStream(srcFile);

zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));

while ((len = in.read(buf)) > 0) {

zip.write(buf, 0, len);

}

}

}

static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws Exception

{

File folder = new File(srcFolder);

for (String fileName : folder.list()) {

if (path.equals("")) {

addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);

}

else {

addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值