【问题标题】:How to use Deflater in java.util.zip如何在 java.util.zip 中使用 Deflater
【发布时间】:2016-07-22 19:34:56
【问题描述】:

您好,我是 Java 新手,我正在尝试使用 java.util.zip 中的 Deflater 压缩字节流。我遵循了来自 Oracle site 的示例。

try {
         // Encode a String into bytes
         String inputString = "blahblahblah";
         byte[] input = inputString.getBytes("UTF-8");

         // Compress the bytes
         byte[] output = new byte[100];
         Deflater compresser = new Deflater();

         compresser.setInput(input);
         compresser.finish();
         int compressedDataLength = compresser.deflate(output);
         compresser.end();

         // Decompress the bytes
         Inflater decompresser = new Inflater();
         decompresser.setInput(output, 0, compressedDataLength);
         byte[] result = new byte[100];
         int resultLength = decompresser.inflate(result);
         decompresser.end();

         // Decode the bytes into a String
         String outputString = new String(result, 0, resultLength, "UTF-8");
     } catch(java.io.UnsupportedEncodingException ex) {
         // handle
     } catch (java.util.zip.DataFormatException ex) {
         // handle
     }

当我运行此代码时,它给了我一个错误,提示 setInput(),finish(),deflate()end() 未定义。这是错误信息

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
The method setInput(byte[]) is undefined for the type Deflater
The method finish() is undefined for the type Deflater
The method deflate(byte[]) is undefined for the type Deflater
The method end() is undefined for the type Deflater

at Deflater.main(Deflater.java:16)

我导入了 java.util.zip 并查看了 Oracle 站点中的文档。它说这些方法存在。

无法弄清楚问题出在哪里。有人可以帮忙吗?

【问题讨论】:

  • 我在教程点上在线执行了完全相同的代码,它运行良好,这些方法存在于 Deflate 类中。 java设置是否有错误,请尝试分别导入Inflate和Deflate。

标签: java zip deflate


【解决方案1】:

问题是你正在调用你的主类Deflater,这对编译器来说是模棱两可的。有两个具有相同名称的类,您的类和 Zip Deflater。您应该将这一行:Deflater compresser = new Deflater(); 更改为此 java.util.zip.Deflater compresser = new java.util.zip.Deflater(); 或简单地更改您的主类的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多