使用java代码解压zip压缩文件时,文件或文件夹出现中文名称是报错
ZipInputStream默认使用UTF_8
// An highlighted block
/**
* Creates a new ZIP input stream.
*
* <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
* decode the entry names.
*
* @param in the actual input stream
*/
public ZipInputStream(InputStream in) {
this(in, StandardCharsets.UTF_8);
}
ZipInputStream可以指定编码
// An highlighted block
/**
/**
* Creates a new ZIP input stream.
*
* @param in the actual input stream
*
* @param charset
* The {@linkplain java.nio.charset.Charset charset} to be
* used to decode the ZIP entry name (ignored if the
* <a href="package-summary.html#lang_encoding"> language
* encoding bit</a> of the ZIP entry's general purpose bit
* flag is set).
*
* @since 1.7
*/
public ZipInputStream(InputStream in, Charset charset) {
super(new PushbackInputStream(in, 512), new Inflater(true), 512);
usesDefaultInflater = true;
if(in == null) {
throw new NullPointerException("in is null");
}
if (charset == null)
throw new NullPointerException("charset is null");
this.zc = ZipCoder.get(charset);
}
将编码设置为GBK解决中文报错问题,解决方法仅供参考
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Zip {
/**
* 解压压缩文件
* @param inputStream 压缩文件流
* @param container
* @throws IOException
*/
public void unZip(InputStream inputStream, Map<String, byte[]> container) throws IOException {
ZipInputStream zip = new ZipInputStream(inputStream, Charset.forName("GBK"));
ZipEntry zipEntry = null;
while ((zipEntry = zip.getNextEntry()) != null) {
String fileName = zipEntry.getName();// 得到文件名称
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] byte_s = new byte[1024];
int num = -1;
while ((num = zip.read(byte_s, 0, byte_s.length)) > -1) {// 通过read方法来读取文件内容
byteArrayOutputStream.write(byte_s, 0, num);
}
container.put(fileName, byteArrayOutputStream.toByteArray());
}
}
}
本文介绍了解决Java中使用ZipInputStream解压ZIP文件时遇到的中文文件名乱码问题。通过设置正确的字符集(如GBK),可以避免在处理包含中文名的文件或目录时出现错误。

241

被折叠的 条评论
为什么被折叠?



