My program performs well in test1
to test3
txt. However, it occurs some error when reading 你好
.txt. I would like to ask how I can modify my program to fix this problem.
Here is the folder structure. A note
folder contains two zip folders which are zipFile1
and zipFile2
. I appreciate if anyone can answer my question.
Operating System: Window 10
Error message: Exception in thread "main" java.util.zip.ZipException: invalid CEN header (bad entry name)
Version of java: openjdk version "1.8.0_191-1-ojdkbuild
├── note
├── zipFile1.zip
├── test1.txt
├── test2.txt
├── zipFile2.zip
├── test3.txt
├── 你好.txt
Here is my program.
public class test {
private static final String SOURCE_FOLDER = "note_folder_path";
static File folder = new File(SOURCE_FOLDER);
static File[] files = folder.listFiles();
final static Charset CHINESE_CHARSET = Charset.forName("MS950");
public static void main(String[] args) throws IOException
{
for (File file:files) {
extractFolder(file.getAbsolutePath());
}
}
public static void extractFolder(String zipFile) throws IOException {
int buffer = 2048;
File file = new File(zipFile);
try (ZipFile zip = new ZipFile(file,CHINESE_CHARSET))
{
String newPath = zipFile.substring(0, zipFile.length() - 4);
new File(newPath).mkdir();
Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
// Process each entry
while (zipFileEntries.hasMoreElements()) {
// grab a zip file entry
ZipEntry entry = zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(newPath, currentEntry);
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
if (!entry.isDirectory()) {
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte[] data = new byte[buffer];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
try (BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, buffer)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
is.close();
}
}
if (currentEntry.endsWith(".zip")) {
// found a zip file, try to open
extractFolder(destFile.getAbsolutePath());
}
}
}
}
}