【问题标题】:How to zip a file that is generated in the code (Java)如何压缩在代码中生成的文件(Java)
【发布时间】:2014-05-20 04:11:05
【问题描述】:

好吧,我正在生成 2 个 .xml 文件,但我想将它们保存在一个文件夹中,并将它们压缩,我不想单独生成它们,而是将它们分开在一个文件夹中并压缩。 d 你明白了吗?

我想将我正在创建的两个文件放入一个文件夹并压缩它。我唯一要保存的是 zip 文件。

String name = fields.find(chooser.getLocation(), "mimic");
                Mimic mimic = getMimic(mimicList.get(0));
                String fileName = chooser.getSelectedFile().toString() + File.separator + "des_" +nombreMimic.substring(0, nombreMimic.length()-4)+ ".xml";
                String config = chooser.getSelectedFile().toString() + File.separator + "cfg_" +nombreMimic.substring(0, nombreMimic.length()-4)+".xml";
                FileOutputStream file;
                FileOutputStream file2;


                file = new FileOutputStream(fileName);
                file2 =new FileOutputStream(config);

                Parser parser;
                parser = new Parser(file,new String[]{});
                parser.render(mimic , fields);
                 JOptionPane.showMessageDialog(null, "Complete!");

                Parser2 parser2;
                parser2 = new Parser2(file2,new String[]{});
                parser2.render(mimic , fields);
                JOptionPane.showMessageDialog(null, "Complete!");   


                FileInputStream inputStream = new FileInputStream(chooser.getSelectedFile().toString() + File.separator + "des_" +nombreMimic.substring(0, nombreMimic.length()-4)+ ".xml");
                ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(nombreMimic.substring(0, nombreMimic.length()-4)+".des"));

                zip.putNextEntry(new ZipEntry(fileName));

                byte [] buffer = new byte [1024];
                int bytesRead;
                while((bytesRead=inputStream.read(buffer))>0){

                zip.write(buffer,0,bytesRead);

                }

                zip.closeEntry();
                zip.close();
                inputStream.close();


            } catch (Exception ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

                JOptionPane.showMessageDialog(null, "Error parsing");
            }
        }
    }
}                                          

【问题讨论】:

  • 您使用的是 Java 7 吗?
  • 没有非常以前。更新不是一个选项,这将被集成到其他东西中

标签: java file oop zip directory


【解决方案1】:

您的问题的答案似乎在这里得到了解答:how to zip a folder itself using java

这里解释了如何使用 Java 压缩文件/文件夹。

您必须将文件保存在文件夹中才能使用,但是一旦压缩,您可以删除此 tutorial 后面的原始文件夹,它使用:

String path = "/path/to/file";
Files.delete(path);

这样,唯一保存的就是 zip 文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-30
    • 2011-05-02
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多