ZipOutPutStream,ZipEntry的返回NULL,当我尝试dezip(ZipOutPu

2019-10-19 02:56发布

我有一个函数来压缩文件,另一个用来解压。 当我尝试解压缩我用我自己的函数生成的压缩包,还有一个空指针异常,因为它没有发现ZipEntry的......当我尝试解压缩使用WinZip,我和dezip功能的归档文件,它的工作原理。

不过,我可以打开并解压缩由我使用WinZip程序生成的档案,文件“内容”是在这里,它的内容为确定。 当我和我的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();
        }
    }

谢谢你的帮助

Answer 1:

你正在写你的zip文件foutput你开始写它通过之前ZipOutputStream zos

我想你应该删除行:

output.writeTo(foutput);


文章来源: ZipOutPutStream, ZipEntry return null when I try to dezip