【问题标题】:Decompress Gzip file and store in variable解压 Gzip 文件并存储在变量中
【发布时间】:2017-08-23 06:43:28
【问题描述】:

我已经搜索了很多从字节到字符串的转换,但我的查询有点不同,请继续阅读。

目前我有一个 gzip 文件,我可以使用http://www.mkyong.com/java/how-to-decompress-file-from-gzip-file/ 中的代码对其进行解压缩。 此代码帮助我将解压缩的输出存储在文件中,但如何将其存储在变量中?我目前正在使用此代码:

public String unGunzipFile(String compressedFile, String decompressedFile) {

        byte[] buffer = new byte[1024];

        try {

            FileInputStream fileIn = new FileInputStream(compressedFile);

            GZIPInputStream gZIPInputStream = new GZIPInputStream(fileIn);

            FileOutputStream fileOutputStream = new FileOutputStream(decompressedFile);
            StringBuffer str = new StringBuffer();
            int bytes_read;
            while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {

                String s = new String(buffer);
                str.append(s);
                fileOutputStream.write(buffer, 0, bytes_read);
            }

            gZIPInputStream.close();
            fileOutputStream.close();

            System.out.println("The file was decompressed successfully!");
            System.out.println(str);
            String final_string = str.toString();
            return final_string;

        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    } 

由于当bytes_read 的长度不是 1024 时,我在末尾将字节转换为字符串,所以我最终在我的 StringBuffer 中得到了一些奇怪的数据,但是在文件中没有这样的数据,因为fileOutputStream.write(buffer, 0, bytes_read); 将其限制为写入更新的部分。 我该如何解决这个问题?

提前致谢。

【问题讨论】:

    标签: java string byte gzipinputstream


    【解决方案1】:

    我建议不要使用 String s = new String(buffer),而是使用

    公共字符串(字节[]字节, 整数偏移量, 整数长度)

    这可能对你有帮助。

    【讨论】:

      【解决方案2】:

      使用String(byte[] bytes, int offset, int length) 构造函数来指定要转换的长度。即

      String s = new String(buffer, 0, bytes_read)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-27
        • 1970-01-01
        • 1970-01-01
        • 2015-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-26
        相关资源
        最近更新 更多