上面的程序怎么完善判断中文格式并正确输出中文文件名
时间: 2024-03-09 12:48:29 浏览: 19
在处理中文文件名时,需要注意编码问题。一般情况下,zip 压缩文件使用的是 GBK 编码,而 Java 默认使用的是 UTF-8 编码。因此,需要将文件名从 GBK 编码转换为 Java 内部的 Unicode 编码,才能正确地创建文件。
下面是一个修改过的 unZip 方法,可以正确处理中文文件名:
```java
public static void unZip(String zipFileName, String outputDirectory) throws Exception {
try {
org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName, "GBK"); // 指定编码
java.util.Enumeration e = zipFile.getEntries();
org.apache.tools.zip.ZipEntry zipEntry = null;
createDirectory(outputDirectory, "");
while (e.hasMoreElements()) {
zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
if (zipEntry.isDirectory()) {
String name = zipEntry.getName();
name = name.substring(0, name.length() - 1);
File f = new File(outputDirectory + File.separator + name);
f.mkdir();
} else {
String fileName = zipEntry.getName();
fileName = new String(fileName.getBytes("GBK"), "UTF-8"); // 将文件名从 GBK 转换为 UTF-8
fileName = fileName.replace('\\', '/');
if (fileName.indexOf("/") != -1) {
createDirectory(outputDirectory, fileName.substring(0, fileName.lastIndexOf("/")));
fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
}
File f = new File(outputDirectory + File.separator + fileName);
f.createNewFile();
InputStream in = zipFile.getInputStream(zipEntry);
FileOutputStream out = new FileOutputStream(f);
byte[] by = new byte[1024];
int c;
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
out.close();
in.close();
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
```
这个方法在创建 ZipFile 对象时指定了 GBK 编码,然后在处理文件名时,先将文件名从 GBK 编码转换为 UTF-8 编码,再进行后续操作。这样就可以正确处理中文文件名了。