GZIP compression to a byte array

后端 未结 6 1151
星月不相逢
星月不相逢 2020-12-13 21:00

I am trying to write a class that can compress data. The below code fails (no exception is thrown, but the target .gz file is empty.)
Besides: I don\'t want to generate

6条回答
  •  無奈伤痛
    2020-12-13 21:13

    You can use the below function, it is tested and working fine.

    In general, your code has serious problem of ignoring the exceptions! returning null or simply not printing anything in the catch block will make it very difficult to debug

    You do not have to write the zip output to a file if you want to process it further (e.g. encrypt it), you can easily modify the code to write the output to in-memory stream

    public static String zip(File inFile, File zipFile) throws IOException {        
        FileInputStream fis = new FileInputStream(inFile);
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zout = new ZipOutputStream(fos);
    
        try {
            zout.putNextEntry(new ZipEntry(inFile.getName()));
            byte[] buffer = new byte[BUFFER_SIZE];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                zout.write(buffer, 0, len);
            }
            zout.closeEntry();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try{zout.close();}catch(Exception ex){ex.printStackTrace();}
            try{fis.close();}catch(Exception ex){ex.printStackTrace();}         
        }
        return zipFile.getAbsolutePath();
    }
    

提交回复
热议问题