我有一个压缩文件的功能和另一个解压缩它的功能。当我尝试解压缩使用自己的函数生成的存档时,会出现空指针异常,因为它没有找到 ZipEntry... 当我尝试使用我的 dezip 函数解压缩使用 winzip 制作的存档时,它可以.
但是我可以用winzip打开和解压缩我的程序生成的档案,文件“内容”在这里,它的内容是好的。仅当我使用解压缩功能尝试时才会出现错误!
这是代码:
public static void zip() {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
/* Code to create the xml */
Properties outFormat = new Properties();
/* properties */
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperties(outFormat);
ByteArrayOutputStream output = new ByteArrayOutputStream();
File file = new File("KOKO.zip");
FileOutputStream foutput = new FileOutputStream(file);
DOMSource domSource = new DOMSource(document.getDocumentElement());
StreamResult result = new StreamResult(output);
transformer.transform(domSource, result);
output.writeTo(foutput);
ZipOutputStream zos = new ZipOutputStream(foutput);
byte[] bytes = output.toByteArray();
ZipEntry entry = new ZipEntry("content");
zos.putNextEntry(entry);
zos.write(bytes);
zos.closeEntry();
zos.close();
/* here the catch clauses */
}
public static void unzip(File zipfile, File folder) throws FileNotFoundException, IOException {
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipfile));
ZipEntry ze = null;
try {
ze = zis.getNextEntry();
System.out.println("path :"+ zipfile.getAbsolutePath());
File f = new File(folder.getAbsolutePath(), ze.getName());
f.getParentFile().mkdirs();
OutputStream fos = new BufferedOutputStream(new FileOutputStream(f));
try {
try {
final byte[] buf = new byte[8192];
int bytesRead;
while (-1 != (bytesRead = zis.read(buf)))
fos.write(buf, 0, bytesRead);
} finally {
fos.close();
}
} catch (final IOException ioe) {
f.delete();
throw ioe;
}
} finally {
zis.close();
}
}
谢谢你的帮助