【问题标题】:Corrupted ZIp is generating in Java损坏的 ZIP 在 Java 中生成
【发布时间】:2020-04-27 17:22:40
【问题描述】:

我已经编写了一段代码来将我的文件以 zip 格式写入并放置在服务器上。现在文件(zip)已成功生成。但它已损坏且无法打开。我在互联网上查看了各种解决方案,例如关闭流和 ZipOutputStream 刷新,但没有任何效果。

请帮忙!

    // Function to write files in ZIP archive..
    public void writeToZip( String ibftDirectory ) throws Exception {

        byte[] buffer = new byte[1024];

        File file = new File(ibftDirectory);
        String zipFileName = file.getName().replace(".csv",".zip");

        try {
            LOGGER.println( "1" );
            FileOutputStream fos = new FileOutputStream(ibftDirectory.replace( ".csv",".zip"));
            LOGGER.println( fos.toString() );
            ZipOutputStream zos = new ZipOutputStream(fos);
            LOGGER.println( zos.toString() );
            zos.putNextEntry(new ZipEntry(file.getName()));
            LOGGER.println( "2" );
            FileInputStream in = new FileInputStream( ibftDirectory );
            LOGGER.println( in.toString() );
            int len;
            while ((len = in.read(buffer)) > 0) {
                LOGGER.println( "value " + len );
                zos.write(buffer, 0, len);
                LOGGER.println( "3" );
            }
            in.close();
            LOGGER.println( "4" );
            zos.finish();
            zos.flush();
            zos.closeEntry();
            LOGGER.println( "5" );
            zos.close();
            fos.close();
            LOGGER.println( "6" );

                } catch (FileNotFoundException ex) {
                    System.err.format("The file %s does not exist", ibftDirectory);
                } catch (IOException ex) {
                    System.err.println("I/O error: " + ex);
                }
     finally {

     }

           }

ibftdirectorypath=/dev/files/myfile.key

【问题讨论】:

    标签: java zip


    【解决方案1】:

    您正在创建一种递归,将文件本身作为ZipEntry

    你可以试试这个代码吗:

    public static void writeToZip(String ibftDirectory) throws Exception {
    
        try (FileInputStream fis = new FileInputStream(ibftDirectory);
                ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ibftDirectory + ".zip"))) {
            zos.putNextEntry(new ZipEntry(ibftDirectory.substring(ibftDirectory.indexOf(File.separator) + 1)));
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            zos.closeEntry();
        }
    }
    

    使用try-with-resource 语法,您可以管理所有打开和关闭操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 2014-08-09
      • 1970-01-01
      相关资源
      最近更新 更多