繁体   English   中英

如何压缩在代码中生成的文件(Java)

[英]How to zip a file that is generated in the code (Java)

好了,我正在生成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压缩文件夹本身

在那里说明了如何使用Java压缩文件/文件夹。

您必须将文件保存在文件夹中才能正常工作,但是一旦将其压缩,就可以按照本教程使用以下内容删除原始文件夹:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM