这里我有几个文件夹(英文,印地文,日文)的Bookfolder。转换英文,印地文,日文到英文.zip,hindi.zip和japanese.zip.Everything工作正常,我保持在Bookfolder中压缩文件和文件夹,这个东西我正在使用java.But当我手动解压缩zip文件ex:english.zip时,右键单击该提取,然后将错误显示为UNEXPECTED END OF ARCHIVE。这是我的代码。
public void foldertToZip(File zipDeleteFile) {
//System.out.println(zipDeleteFile);
File directoryToZip = zipDeleteFile;
List<File> fileList = new ArrayList<>();
//System.out.println("---Getting references to all files in: " + directoryToZip.getCanonicalPath());
getAllFiles(directoryToZip, fileList);
//System.out.println("---Creating zip file");
writeZipFile(directoryToZip, fileList);
//System.out.println("---Done");
}
public static void getAllFiles(File dir, List<File> fileList) {
try {
File[] files = dir.listFiles();
for (File file : files) {
fileList.add(file);
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
getAllFiles(file, fileList);
} else {
System.out.println("file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
}
}
public static void writeZipFile(File directoryToZip, List<File> fileList) {
try {
//try (FileOutputStream fos = new FileOutputStream(directoryToZip.getName() + ".zip"); ZipOutputStream zos = new ZipOutputStream(fos)) {
File path = directoryToZip.getParentFile();
File zipFile = new File(path, directoryToZip.getName() + ".zip");
try (FileOutputStream fos = new FileOutputStream(zipFile)) {
ZipOutputStream zos = new ZipOutputStream(fos);
for (File file : fileList) {
if (!file.isDirectory()) { // we only zip files, not directories
addToZip(directoryToZip, file,zos);
}
}
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException,
IOException {
try (FileInputStream fis = new FileInputStream(file)) {
String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,
file.getCanonicalPath().length());
System.out.println("Writing '" + zipFilePath + "' to zip file");
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
}
}`
虽然我正在提取新的zip文件(例如:english.zip)但它显示错误是意外的结束(我认为不会完全压缩)&#39;
答案 0 :(得分:4)
您需要在ZipOutputStream
方法中关闭writeZipFile()
;
for (File file : fileList) {
if (!file.isDirectory()) { // we only zip files, not directories
addToZip(directoryToZip, file,zos);
}
}
//here close zos
zos.close();