ava zip解压 中文_java解压ZIP 解决中文乱码 (GBK和UTF-8)
时间: 2024-03-09 12:48:09 浏览: 101
在Java中解压ZIP文件时,如果文件名或内容包含中文字符,可能会出现乱码问题。解决这个问题可以参考以下步骤:
1. 使用ZipInputStream类读取ZIP文件,并使用ZipEntry类获取ZIP文件中的每个文件。
2. 如果ZIP文件的编码格式为GBK,则可以使用以下代码进行解压:
```java
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile), Charset.forName("GBK"));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String fileName = zipEntry.getName();
fileName = new String(fileName.getBytes("GBK"), "UTF-8");
if (zipEntry.isDirectory()) {
File folder = new File(outputFolder, fileName);
folder.mkdirs();
} else {
File file = new File(outputFolder, fileName);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = zipInputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
}
zipInputStream.close();
```
3. 如果ZIP文件的编码格式为UTF-8,则可以使用以下代码进行解压:
```java
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile), Charset.forName("UTF-8"));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String fileName = zipEntry.getName();
if (zipEntry.isDirectory()) {
File folder = new File(outputFolder, fileName);
folder.mkdirs();
} else {
File file = new File(outputFolder, fileName);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = zipInputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
}
zipInputStream.close();
```
通过以上代码,可以解决中文乱码问题。
阅读全文