我有一个压缩文件的功能,另一个解压缩它。当我尝试解压缩我用自己的函数生成的存档时,有一个空指针异常,因为它没有找到ZipEntry ...当我尝试使用我的dezip函数解压缩使用winzip创建的存档时,它可以正常工作
但是我可以使用winzip打开并解压缩我的程序生成的存档,文件“content”在这里,其内容正常。只有当我使用我的dezip函数尝试它时才会出现错误!
以下是代码:
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();
}
}
感谢您的帮助
答案 0 :(得分:0)
在您通过foutput
ZipOutputStream zos
我认为你应该删除行:
output.writeTo(foutput);