Hi i'm new to java and i'm trying to compress a byte stream using Deflater
in java.util.zip
.I followed an example from 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
}
When I run this code it gives me an error saying setInput()
,finish()
,deflate()
and end()
is not defined. Here is the error message
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)
I imported java.util.zip
and looked in the Documentation in Oracle site.It says those methods exist.
Can't figure out where the problem is. Can someone help.
The problem is you are calling your main class Deflater
, which is ambiguous for the compiler. There are two classes with the same name, your class and the Zip Deflater
. You should change this line: Deflater compresser = new Deflater();
to this java.util.zip.Deflater compresser = new java.util.zip.Deflater();
or simply change the name of your main class.