【问题标题】:Zip file not getting generated未生成 Zip 文件
【发布时间】:2019-06-13 14:47:08
【问题描述】:

我的 springboot 应用程序中有这个方法,它在 custom_users 目录中生成 3 个 CSV 文件(与 Employee、Customer 和 Building 相关),并在其名称后附加时间戳,如下所示。 现在它只生成两个 CSV 文件(公司和建筑相关),因为我正在测试employee_custom_file 的 zip 文件相关转换,如下所示。

在使用CSVWriter(来自opencsv)将员工相关内容转换为zip文件时,谁能告诉我我做错了什么?我期待一个 zip 文件与其他 2 个 CSV 文件一起显示,但由于某种原因,只生成了 2 个 CSV 文件。

下面代码中的这部分基本上没有按我的预期工作:

ZipEntry entry = new ZipEntry(file.getFileName().toString());
zos.putNextEntry(entry);
try {
    CSVWriter writer = new CSVWriter( new OutputStreamWriter(zos,StandardCharsets.UTF_8)))) {
        writer.writeAll(rsDemo, true);
    }

================================================ =======================

public void sendMessage(String msg) throws DaoException {

        DataSource ds = null;
        Connection conn = null;
        PreparedStatement pstmt = null;
        PreparedStatement pstmtEmployee = null;
        PreparedStatement pstmtCompany = null; 
        PreparedStatement pstmBuilding = null; 

        ResultSet rs = null;
        ResultSet rsDemo = null;
        ResultSet rsCompany = null;
        ResultSet rsBuildings = null;


         String[] parts = msg.split("#");
         String requestID = parts[0].trim();
         String userName = parts[1].trim();
         String applicationName = parts[2].trim();

        logger.info("Request ID "+requestID);
        logger.info("User Name "+userName);
        logger.info("Application Name "+applicationName);



         try {

                ds = jdbcTemplate.getDataSource();
                conn = ds.getConnection();  

                /*===========================================================================*/
                /*    Code to generate a employee CSV file              */ 
                /*===========================================================================*/
                pstmtEmployee = conn.prepareStatement(getPatientEmployeeSQL);
                pstmtEmployee.setString(1, requestID);
                rsDemo = pstmtEmployee.executeQuery();

                ResultSetMetaData rsmd = rsDemo.getMetaData();

                 FileOutputStream fos = new FileOutputStream("your_files.zip");
                 BufferedOutputStream bos = new BufferedOutputStream(fos);
                 ZipOutputStream zos = new ZipOutputStream(bos);

                 Path dir = Paths.get("/srv/custom_users", userName);
                 Files.createDirectories(dir);

                 Path file = dir.resolve("employee_custom_file" + unixTimestamp + ".csv");
                 /*try (CSVWriter writer = new CSVWriter(Files.newBufferedWriter(file))) {
                     writer.writeAll(rsDemo, true);
                 }*/
                 ZipEntry entry = new ZipEntry(file.getFileName().toString());
                 zos.putNextEntry(entry);
                 try (CSVWriter writer = new CSVWriter(new OutputStreamWriter(zos,StandardCharsets.UTF_8)))) {
                     writer.writeAll(rsDemo, true);
                 }


                 logger.info("Employee File Generated");



                 /*===========================================================================*/
                 /*    Code to generate a company CSV file                                      */ 
                 /*===========================================================================*/

                pstmtCompany = conn.prepareStatement(getCompanySQL);
                pstmtCompany.setString(1, requestID);
                rsCompany = pstmtCompany.executeQuery();

                ResultSetMetaData rsmdFacts = rsCompany.getMetaData();


                 Path filecompany = dir.resolve("company_custom_file_" + unixTimestamp + ".csv");
                 try (CSVWriter writer = new CSVWriter(Files.newBufferedWriter(filecompany))) {
                     writer.writeAll(rsCompany, true);
                 }

                 logger.info("Company CSV File Generated");


                 /*===========================================================================*/
                 /*    Code to generate a building CSV file                                 */ 
                 /*===========================================================================*/

                 pstmBuilding = conn.prepareStatement(getBuildingSQL);
                  pstmBuilding.setString(1, requestID);
                  rsBuildings = pstmBuilding.executeQuery();

                   ResultSetMetaData rsmdBuildings = rsBuildings.getMetaData();


                    Path fileBuildings = dir.resolve("building_custom_file_" + unixTimestamp + ".csv");
                     try (CSVWriter writer = new CSVWriter(Files.newBufferedWriter(fileBuildings))) {
                         writer.writeAll(rsBuildings, true);
                     }

                    logger.info("Buildings CSV File Generated");




                }
            catch(Throwable th) {
                throw new DaoException(th.getMessage(), th);
            }
            finally {
                //resource Closing statements

            }   



    }

【问题讨论】:

  • 我相信ZipOutputStream不应该被用来不断地写信给它。完成写入文件并随后将其压缩
  • 谢谢,但我不想将文件写入磁盘然后压缩。基本上,我正在尝试即时压缩 csv 内容。
  • 是的,我看过那篇文章,但试图弄清楚我在上面的代码中面临的确切问题。

标签: java fileoutputstream opencsv zipoutputstream


【解决方案1】:

您是否调用了代码示例中省略的closeEntry

请注意,写入 zip 输出流的内容是支持输出流的任何内容。 'Writing' 条目写入 zip 流,而不是磁盘,除非输出流是这样设置的。

来自ZipOutputStream

/**
 * Closes the current ZIP entry and positions the stream for writing
 * the next entry.
 * @exception ZipException if a ZIP format error has occurred
 * @exception IOException if an I/O error has occurred
 */
public void closeEntry() throws IOException {

【讨论】:

  • 我还没有打电话给closeEntry。我只是想为我的测试目的生成一个 zip 文件。如果出于测试目的需要这样做,请建议我应该在何时何地打电话?
  • 在为单个条目写入所有数据后,调用“closeEntry”以完成条目的写入。根据代码示例,如果“writeAll”写入了所有用于条目的数据,那么在“writeAll”之后将是调用的位置。
  • 所以我添加了这两行writer.flush();zos.closeEntry();,就在writer.writeAll(rsDemo, true);这一行的下方,但它仍然没有生成一个zip文件。
  • API 的另一部分是在写入所有条目后对 zip 输出流调用“finish()”。 (最后,在 zip 输出流上调用“关闭”。)
  • 作为测试替代方案,您可以尝试写入非 zip 类型的输出流,看看是否成功传输数据。这会将 zip API 使用的任何问题与传输步骤分开。
【解决方案2】:

我让它工作了。我的这行代码FileOutputStream fos = new FileOutputStream("your_files.zip"); 造成了问题,因为我没有在任何地方使用我的dir 变量。因此我不得不像这样使用它来使其工作:

OutputStream fos = Files.newOutputStream(dir.resolve("your_files.zip"));
BufferedOutputStream bos = new BufferedOutputStream(fos);
ZipOutputStream zos = new ZipOutputStream(bos);

【讨论】:

    猜你喜欢
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    相关资源
    最近更新 更多