Friday, October 14, 2011

Compressing and Decompressing String in Java using GZIP streams

Following code can be used to compress or decompress any data in Java using the GZIP streams - java's built in zip streams.
    public static String compress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        System.out.println("String length : " + str.length());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes());
        gzip.close();
        String outStr = out.toString("ISO-8859-1");
        System.out.println("Output String lenght : " + outStr.length());
        return outStr;
     }
    
    public static String decompress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        System.out.println("Input String length : " + str.length());
        GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str.getBytes("ISO-8859-1")));
        BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "ISO-8859-1"));
        String outStr = "";
        String line;
        while ((line=bf.readLine())!=null) {
          outStr += line;
        }
        System.out.println("Output String lenght : " + outStr.length());
        return outStr;
     }
  
     public static void main(String[] args) throws IOException {
        String filePath = ".\response.txt";
        
        String string = getFileData(filePath);
        System.out.println("after compress:");
        String compressed = compress(string);
        System.out.println(compressed);
        System.out.println("after decompress:");
        String decomp = decompress(compressed);
        System.out.println(decomp);
 
      }
     
     public static String getFileData(String filepath) throws FileNotFoundException,
                                                           IOException {
       BufferedReader bf = new BufferedReader(new FileReader(filepath));
       String data="";
       String line;
       while ((line=bf.readLine())!=null) {
         data += line;
       }
       return data;
     }

54 comments:

  1. Thanks a lot for your post :)

    ReplyDelete
  2. Excellent. Good Work.

    ReplyDelete
  3. If UTF-8 is used instead of ISO-8859-1 then I/O exception is thrown..

    ReplyDelete
  4. Neither format is ideal. UTF-8 and ISO-8859-1 are String formats. This means that they are ways of interpreting byte data. For example, if I told you "65," you'd have no idea what that meant. UTF-8 is a way of interpreting it. For example, 65 could represent the letter A. Gzip operates on bytes, not strings. This means that you can Gzip an image, which is not text. Thus, the data outputted by Gzip may happen to comply with ISO-8859-1, but that does not mean that you would be getting any meaningful result.

    ReplyDelete
  5. Guys, you saved my weekend :-D
    thanks for the post

    ReplyDelete
  6. If you want decompessed string in UTF-8 just change the second format to UTF-8 as it is decompessed in ISO-8859-1 but read in UTF-8.

    Thank Pankaj for this useful post.

    ReplyDelete
  7. Thank you very much. Saved mu Weekend.

    ReplyDelete
  8. The code to compress just works if returns byte[] and not String, because toString() may miss some special chars. These works:
    - byte[] compress(String)
    - String decompress(byte[])

    ReplyDelete
  9. Thank you. Found it interesting and useful. Java is a general purpose, high-level, class-based and object-oriented programming language. And we are the best Java training institute in Chennai.

    ReplyDelete
  10. Crypto-currency as a modern form of the digital asset has received a worldwide acclaim for easy and faster financial transactions and its awareness among people have allowed them to take more interest in the field thus opening up new and advanced ways of making payments. Crypto.com Referral Code with the growing demand of this global phenomenon more,new traders and business owners are now willing to invest in this currency platform despite its fluctuating prices however it is quite difficult to choose the best one when the market is full. In the list of crypto-currencies bit-coins is one of the oldest and more popular Crypto.com Referral Code for the last few years. It is basically used for trading goods and services and has become the part of the so-called computerized block-chain system allowing anyone to use it thus increasing the craze among the public, Crypto.com Referral Code.

    Common people who are willing to purchase BTC can use an online wallet system for buying them safely in exchange of cash or credit cards and in a comfortable way from the thousands of BTC foundations around the world and keep them as assets for the future. Due to its popularity, many corporate investors are now accepting them as cross-border payments and the rise is unstoppable. With the advent of the internet and mobile devices,information gathering has become quite easy as a result the BTC financial transactions are accessible and its price is set in accordance with people’s choice and preferences thus leading to a profitable investment with Crypto.com Referral Code. Recent surveys have also proved that instability is good for BTC exchange as if there is instability and political unrest in the country due to which banks suffer then investing in BTC can surely be a better option. Again bit-coin transaction fees are pretty cheaper and a more convenient technology for making contracts thus attracting the crowd. The BTC can also be converted into different fiat currencies and is used for trading of securities, for land titles, document stamping, public rewards and vice versa.

    Another advanced block-chain project is Ethereumor the ETH which has served much more than just a digital form of crypto-currency Crypto.com Referral Code and its popularity in the last few decades have allowed billions of people to hold wallets for them. With the ease of the online world,the ETH have allowed the retailers and business organizations to accept them for trading purposes, therefore, can serve as the future of the financial system.

    ReplyDelete
  11. You will be surprised if you know how easy and fun it is. data science course syllabus

    ReplyDelete
  12. Truly, this article is really one of the very best in the history of articles. I am a antique ’Article’ collector and I sometimes read some new articles if I find them interesting. And I found this one pretty fascinating and it should go into my collection. Very good work!
    data science course in India

    ReplyDelete
  13. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
    Artificial Intelligence Course

    ReplyDelete
  14. Archie 420 Dispensary is a trusted Cannabis dispensary base in Los Angeles California USA. It is one of the top dispensary in this part of the country. They do deliver Marijuana in the USA and to over 25 countries in the world. Jack herer buds for sales You can always visit their dispensary in Los Angeles using the address on their website. Place your order and get served by the best dispensary in the planet. Have fun.

    ReplyDelete
  15. Crystal online pharmacy is a trusted online drug store with a wide range of products to suit the needs of our clients. Buy Drugs online Crystal Pharmacy do strive to offer the best service and ship products world wide. All the products listed on our website are Ava in stock. Expect your order to be processed Immediately when you send us your request. We deal with varieties of drugs for our customers satisfaction. We cross barriers with our products and struggle hard to meet human satisfaction. When shopping with us, Be safe and secured and you will realize how swift we are with our services.

    ReplyDelete
  16. Universal Gun sales is a trusted Firearm company base in Los Angeles California USA. It is one of the top Firearms Company in this part of the country. Buy Gun suppressor online They do offer the best firearms deal in the USA and to over 25 countries in the world. You can always visit their shop in Los Angeles using the address on their website. Place your order and get served by the best Firearm Company in the planet. Have fun.

    ReplyDelete
  17. PG SLOT มีเกมหลากหลายให ้เลือก พรอ้ มกราฟฟิกแอนนเิมชนั่ สวยงามทสี่ ดุ ในยคุ นี้แจ็คพอตแตกง่าย pgslot โปรโมชนั่ พเิศษส าหรับทงั้สมาชก เกา่ และสมาชกิ ใหม่ ระบบฝาก-ถอนเงินออโต ้เงินเข ้าเร็วทันใจมีแอดมิ ดูแลตลอด 24 ชวั่ โมง ต ้องที่ pgslot.bid มั่นคงจ่ายจริง ไม่ว่าคุณจะถอนเงิ มากมายเท่าไหร่ ทางเว็บจ่ายเต็มไม่มีหัก pgslot ปั่นง่ายแตกง่าย

    PG SLOT ผู ้ให ้บริการเว็บตรง ที่แตกง่ายที่สุด ปั่นสนุก ฝากเงินรับเครดิตฟร สูงสุด 15000 บาท สมัคร พีจีสล็อต หรือ PGSLOT กับเราเพื่อความมั่นคงของคุณเอง.

    ReplyDelete
  18. What a thrilling post. It is extremely chock-full of useful information. Thanks for such a great info. Direct Response Copywriter

    ReplyDelete
  19. We're more than just a san diego web design Company. With our full-service digital marketing packages, you can get the most out of your online marketing

    ReplyDelete
  20. If you print the document, and then spot an error or decide you need to add more to it, you can make the changes you need to make and then reprint renting impresoras

    ReplyDelete
  21. An Advanced Guide to Dealer Tells & Hole Carding - 안전토토사이트 먹튀검증업체 스포츠중계 for Advanced Players

    ReplyDelete
  22. your article is very helpful. you can visit my website.
    Thank you for helping people get the information they need. Great stuff as usual. Keep up the great work!
    This is a very helpful site for anyone, each and every man can easily operate this site and can get
    The overview of your website is pretty good, not to mention what it does.의성아로마
    영양아로마
    청도아로마
    고령아로마
    성주아로마
    예천아로마
    봉화아로마
    In the content! Your are so good. Your work is amazing.

    ReplyDelete
  23. Just 99 Web Design offers affordable web design packages for every business, from basic one-page websites to full eCommerce website design services. inexpensive web design companies

    ReplyDelete
  24. Ýnternet üzerinden gerçek bir casino hizmetine ulaþabilirsiniz. Gerçek casino salonlarýndan canlý casino hizmeti veren özel siteleri bulunmakta. Canlý casino siteleri gerçek casino salonlarýndan kullanýcýlarýna gerçek paralar üzerinden casino oyunlarý sunmakta canlı casino. Oyuncular internete baðlý olduklarý her yerden casino oyunlarý oynayabilmekte. Lakin bahsettiðimiz ve bahsedeceðimiz hizmetleri almak için doðru casino siteleri seçmeniz gerekmekte. Doðru siteleri yani güvenilir casino siteleri tercih ederek hem gerçek bir hizmet alýn hem de kazançlarýnýzý sorunsuz bir þekilde çekin.
    Sektörün en gözde casino þirketleri sayfamýzda paylaþýlmakta. Casino siteleri giriþ butonlarý üzerinden sitelere ulaþabilirsiniz. Sizlere sitelerin hizmetleri hakkýnda bilgiler vereceðiz. Sitelerin sunduklarý hizmetleri, bonuslarý ve finansal araçlarý hakkýnda bilgileri sizlere sunacaðýnýz. En iyi canlı casino sayfamýzdan ulaþabilirsiniz.
    Canlý casino
    Paylaþtýðýmýz siteler oyuncularýna gerçek casino salonlarýndan hizmet sunmakta. Oyuncular BlackJack, rulet, poker gibi casino masa oyunlarýný 4K görüntü kalitesi üzerinden gerçek casino salonlarýndan oynamakta. Ayrýca masa oyunlarý yanýnda özel oyunlarda bulunmakta. Canlý olarak sunulan oyunlar 4K görüntü kalitesi üzerinden oyunculara aktarýlmakta. Oyunlarýn sunumlarý canlý kurpiyerlerin sunumlarýyla yapýlmakta. Canlý casino oyunlarý kurpiyerlerin sunumlarýyla oynanmakta. Ayrýca masalarda bulunan herkes sizler gibi gerçek oyuncudur. Asla sitelerde bot hesaplarý bulunmaz. Herkes gerçek oyuncudur. Ayrýca odalarda sohbet bölümleri bulunmakta. Canlý casino
    oyunlarý oynanýrken ayný zamanda diðer oyuncular ile sohbet edebilirsiniz.
    Sitelerde poker, blackjack, rulet gibi onlarca farklý casino masa oyunlarý. Özel olarak hazýrlanan crayz time gibi canlý casino oyunlarý. Aviator, zeplin gibi popüler oyunlar ve binlerce farklý slot oyunlarý bulunmakta. Oyuncular istedikleri oyunlarý istedikleri bet üzerinden oynayabilmekte. Casino siteleri gerçek kumarhanelerdeki oyunlarý ve hatta daha fazlasýný kullanýcýlarýna sunmakta canlı casino.
    Lakin unutmayýn bahsettiðimiz hizmetleri en iyi casino siteleri için geçerli. Her canlý casino sitesi ayný hizmeti vermemekte. Bundan dolayý önünüze gelen her casino sitesi giriþ yapmayýn. Güvenilir casino siteleri giriþ yaparak gerçek bir hizmete ulaþýn.
    Oyuncular casino oyunlarýndan saðladýklarý kazançlarýný sorun yaþamadan çekebilmekte. Ayrýca istedikleri finansal yöntemi kullanarak seçebilmekte. Siteler oyuncular onlarca farklý finansal araç sunmakta. Kullanýcýlar istedikleri yöntemleri kullanarak para yatýrma ve çekme iþlemlerini kolay bir þekilde canlı casino yapabilmekte.
    Casino siteleri onlarca farklý bonus da vermekte. Yeni kayýt olan kullanýcýlar deneme bonusu ve free spin alarak bedava casino oyunlarý oynama fýrsatý yakalamakta. Ýlk yatýrýmlarýna özel casino hoþgeldin bonusu. Her yatýrýmlarýna özel casino yatýrým bonusu. Þansýz günlerinde ise casino kayýp bonusu alabilmekte. Ayrýca bahsettiðimiz bonuslar dýþýnda farklý casino bonuslarý da bulunmakta canlı casino.
    Deneme bonusu veren casino siteleri sayesinde kayýt olarak yatýrým yapamadan bedava casino oyunlarý oynayabilirsiniz. Siteler yeni üyelerine özel olarak bedava bonus vermekte.
    Bonusu alan kullanýcýlar bedava bir þekilde casino oyunlarý oynayarak ayrýca kazançlarýnýzý çekebilirsiniz.
    Güvenilir canlý casino siteleri sayesinde avantajlý bir hizmete ulaþýn.

    ReplyDelete
  25. Ghostwriters are basically the professionals who write the content for you but does not put their name on the work or takes any credit for their writing. Ghost writing simply means professional who are hired to write your memories, blogs or speeches and many more such scripts for you and your brand but doesn’t tag themselves on the work or you can say they don’t take the credit for their work and you are not allowed to share your work anywhere else. Ebook Writing Services

    ReplyDelete
  26. The galvanometric system offers excellent stability for engraving, rapid scanning, and turnaround. Optics Trends

    ReplyDelete