IT/Java

.gz 파일 압축 풀기 (GZIPInputStream, GZIPOutputStream)

성준하이 2023. 9. 15. 08:58
반응형

//////////////main 함수

public static void main(String[] args) {

    String file = "/Users/test/test.txt";

    String gzipFile = "/Users/test/test.txt.gz";

    String newFile = "/Users/test/test_new.txt";

 

    compressGzipFile(file, gzipFile);

 

    decompressGzipFile(gzipFile, newFile);

}

 

//////////////압축풀기 함수

private static void decompressGzipFile(String gzipFile, String newFile) {

    try {

        FileInputStream fis = new FileInputStream(gzipFile);

        GZIPInputStream gis = new GZIPInputStream(fis);

        FileOutputStream fos = new FileOutputStream(newFile);

        byte[] buffer = new byte[1024];

        int len;

        while((len = gis.read(buffer)) != -1){

            fos.write(buffer, 0, len);

        }

        //close resources

        fos.close();

        gis.close();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

 

//////////////압축하기 함수

private static void compressGzipFile(String file, String gzipFile) {

    try {

        FileInputStream fis = new FileInputStream(file);

        FileOutputStream fos = new FileOutputStream(gzipFile);

        GZIPOutputStream gzipOS = new GZIPOutputStream(fos);

        byte[] buffer = new byte[1024];

        int len;

        while((len=fis.read(buffer)) != -1){

            gzipOS.write(buffer, 0, len);

        }

        //close resources

        gzipOS.close();

        fos.close();

        fis.close();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

반응형