【发布时间】: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。