简体   繁体   中英

How to use Deflater in java.util.zip

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM