'Java'에 해당되는 글 22건

  1. 2013.11.26 Java7 zip 파일 압축
Java2013. 11. 26. 14:35
반응형

 Java7부터 새로운 NIO가 추가되면서 새로운 파일압축(zip)도 가능하게 되었다. 간단하게 압축, 압축해제에 대해서 알아보도록 하겠습니다.

 

 먼저, 간단한 압축 예제입니다.


 public static void zipFiles() throws IOException {

    //압축파일을 배치할 경로 생성
    final String zipPath = "D:/work/ziptest";
    final Path path = Paths.get(zipPath);
    Files.createDirectories(path);

    //압축 파일 생성 옵션(새로생성, 파일명 캐릭터셋등)
    final Map<String, String> zipProp = new HashMap<>();
    zipProp.put("create", Boolean.toString(true));
    zipProp.put("encoding", Charset.defaultCharset().displayName());

    //압축파일 경로
    URI zipFileUri = URI.create("jar:file:/" + zipPath + "/zipfile.zip");

    //압축파일 파일 시스템생성
    try (FileSystem zipfs = FileSystems.newFileSystem(zipFileUri, zipProp)) {
        final Path targetFile = Paths.get("D:/work/a.txt");
        final Path targetPath = zipfs.getPath("/data/a.txt");
        Files.createDirectories(targetPath);

        //압축 파일안에 압축할 파일 넣기
        Files.copy(targetFile, targetPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (Exception  e) {
        e.printStackTrace();
    }
}


 위의 예제를 참조하면 간단한 파일 압축을 할 수 있을것이라고 생각된다. 간단하게 개념을 정리해 보자면 압축파일 자체를 새로운 파일시스템(간단하게 드라이브)의 개념으로 작동하게 하고 있다고 생각된다. 압축할 파일을 하나의 드라이브로 놓고 그 안으로 파일을 복사해서 넣는 것으로 간단하게 파일 압축을 구현하고 있다.


 아래의 압축해제의 경우는 압축할 경우를 반대로 생각하면 될듯하다.


public static void unzipFiles() throws IOException {

    //압축 해제할 경로 생성
    final Path destPath = Paths.get("D:/work/unzip");
    if (!Files.exists(destPath)) {
        Files.createDirectories(destPath);
    }

    final Map<String, String> prop = new HashMap<>();
    prop.put("create", Boolean.toString(false));

    URI zipFileUri = URI.create("jar:file:/D:/work/ziptest/zipfile.zip");

    //압축 해제할 파일의 파일시스템 취득

    try (FileSystem zipfs = FileSystems.newFileSystem(zipFileUri, prop)) {
        final Path root = zipfs.getPath("/");

        //압축 파일 내부 탐색하면서 복사
        Files.walkFileTree(root, new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult visitFile(final Path file
            , final BasicFileAttributes attrs ) throws IOException {
                final Path destFile = Paths.get(destPath.toString(), file.toString());
                Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
            @Override
            public FileVisitResult preVisitDirectory(final Path dir
            , final BasicFileAttributes attrs ) throws IOException {
                final Path dirToCreate = Paths.get(destPath.toString()
                    , dir.toString()
                );
                if(Files.notExists(dirToCreate)){
                    Files.createDirectory(dirToCreate);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (Exception  e) {
        e.printStackTrace();
    }
} 


 압축 해제할 파일의 파일시스템을 취득후 압축할 경우와 반대로 해제할 경로로 복사해주면 간단하게 압축 해제가 가능하다. Java7에서 추가된 구현이기 때문에 이전버전을 사용해야 한다면 물론 다른 구현체를 이용해야 한다.


※이전 버전에도 파일 압축 구현은 존재하였으나 파일명의 인코딩을 지정할 수 없는 문제가 존재하였다. 시간이 된다면 다음 기회에 알아 보도록 하겠습니다.

Posted by Reiphiel