您好我是java的新手,并且我尝试使用Deflater
中的java.util.zip
压缩字节流。我按照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网站上的文档。它说这些方法存在。
无法找出问题所在。有人可以帮忙。
答案 0 :(得分:2)
问题是你正在调用主类Deflater
,这对编译器来说是不明确的。有两个具有相同名称的类,您的类和Zip Deflater
。您应该将此行:Deflater compresser = new Deflater();
更改为此java.util.zip.Deflater compresser = new java.util.zip.Deflater();
,或者只需更改主要类的名称。