FAQ

Java

JSP

Servlet


Advertisement



How to make a gzip file in Java?

To create a GZIP file, you can use GZIPOutputStream class provided by java.util.zip package. Here is an example,

        String outFilename = "GZIPTest.txt.gz";
        String inFilename = "Test.txt";
        BufferedWriter bufferedWriter = null;
        BufferedReader bufferedReader = null;
        try {
           
            //Construct the BufferedWriter object
            bufferedWriter = new BufferedWriter(
                                 new OutputStreamWriter(
                                     new GZIPOutputStream(new FileOutputStream(outFilename))
                                 ));

            //Construct the BufferedReader object
            bufferedReader = new BufferedReader(new FileReader(inFilename));
           
            String line = null;
           
            // from the input file to the GZIP output file
            while ((line = bufferedReader.readLine()) != null) {
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
           
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            //Close the BufferedWrter
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
           
            //Close the BufferedReader
            if (bufferedReader != null ){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |