문제

Groovy에는 Zip 파일을 처리하기 위한 지원 기능이 내장되어 있습니까(그루비 방식)?

아니면 Groovy에서 Zip 파일을 처리하려면 Java의 java.util.zip.ZipFile을 사용해야 합니까?

도움이 되었습니까?

해결책

Afaik, 기본적인 방법이 없습니다. 그러나 체크 아웃 이 기사 추가 방법에 대해 .zip(...) 파일에 대한 방법은 찾고있는 것과 매우 가깝습니다. 당신은 단지 만들어야 할 것입니다 .unzip(...) 방법.

다른 팁

아마도 Groovy에는 zip 파일에 대한 '기본' 지원이 없지만 zip 파일을 사용하는 것은 여전히 ​​매우 사소한 일입니다.

나는 zip 파일로 작업하고 있으며 다음은 내가 사용하는 논리 중 일부입니다.

def zipFile = new java.util.zip.ZipFile(new File('some.zip'))

zipFile.entries().each {
   println zipFile.getInputStream(it).text
}

다음을 사용하여 추가 논리를 추가할 수 있습니다. findAll 방법:

def zipFile = new java.util.zip.ZipFile(new File('some.zip'))

zipFile.entries().findAll { !it.directory }.each {
   println zipFile.getInputStream(it).text
}

내 경험상,이를 수행하는 가장 좋은 방법은 앤트 빌더를 사용하는 것입니다.

def ant = new AntBuilder()   // create an antbuilder

ant.unzip(  src:"your-src.zip",
            dest:"your-dest-directory",
            overwrite:"false" )

이런 식으로 당신은 모든 복잡한 일을 할 책임이 없습니다. 개미는 당신을 위해 그것을 돌 봅니다. 분명히 더 세분화 된 것이 필요하다면 이것은 작동하지 않지만 대부분의 경우 대부분의 경우이 파일을 압축 해제합니다.

Antbuilder를 사용하려면 ClassPath에 Ant.jar 및 Ant-Launcher.jar를 포함하십시오.

Groovy Common Extension 프로젝트는 Groovy 2.0 이상에 대한이 기능을 제공합니다. https://github.com/timyates/groovy-common-extensions

이 기사는 앤트 빌더 예제를 확장합니다.

http://preferisco.blogspot.com/2010/06/using-goovy-antbuilder-to-zip-unzip.html

그러나 교장의 문제 - 그루비/Java에서 새로운 패싯을 조사 할 때 사용할 수있는 모든 속성, 클로저, 맵 등을 찾을 수있는 방법이 있습니까? 정말 유용한 것들이 많이있는 것 같지만 숨겨진 보물을 잠금 해제하는 방법은 무엇입니까? NetBeans/Eclipse Code-Complete 기능은 이제 우리가 가진 새로운 언어 풍부함에서 절망적으로 제한적으로 보입니다.

Antbuilder를 사용하는 압축은 좋은 방법입니다.
두 번째 옵션은 타사 라이브러리를 사용하는 것입니다. Zip4J

질문을 다른 방향으로 약간 가져 왔지만, 내가 만들고있는 DSL에 Groovy를 사용하기 시작했지만 결국 Gradle을 시작점으로 사용하여 내가하고 싶은 많은 파일 기반 작업을 더 잘 처리했습니다 (예 : ., 압축 및 기타 파일, 다른 프로그램 실행 등). Gradle은 Groovy가 할 수있는 일을 바탕으로 플러그인을 통해 더 확장 할 수 있습니다.

// build.gradle
task doUnTar << {
    copy {
        // tarTree uses file ext to guess compression, or may be specific
        from tarTree(resources.gzip('foo.tar.gz'))
        into getBuildDir()
    }
}

task doUnZip << {
    copy {
        from zipTree('bar.zip')
        into getBuildDir()
    }
}

예를 들어 (이것은 추출합니다 bar.zip 그리고 foo.tgz 디렉토리로 build):

$ gradle doUnZip
$ gradle doUnTar

아래 그루비 방법은 특정 폴더 (c : 폴더)로 압축을 풀어줍니다. 도움이 되었기를 바랍니다.

import org.apache.commons.io.FileUtils
import java.nio.file.Files
import java.nio.file.Paths
import java.util.zip.ZipFile

def unzipFile(File file) {
    cleanupFolder()
    def zipFile = new ZipFile(file)
    zipFile.entries().each { it ->
        def path = Paths.get('c:\\folder\\' + it.name)
        if(it.directory){
            Files.createDirectories(path)
        }
        else {
            def parentDir = path.getParent()
            if (!Files.exists(parentDir)) {
                Files.createDirectories(parentDir)
            }
            Files.copy(zipFile.getInputStream(it), path)
        }
    }
}

private cleanupFolder() {
    FileUtils.deleteDirectory(new File('c:\\folder\\'))
}
def zip(String s){
    def targetStream = new ByteArrayOutputStream()
    def zipStream = new GZIPOutputStream(targetStream)
    zipStream.write(s.getBytes())
    zipStream.close()
    def zipped = targetStream.toByteArray()
    targetStream.close()
    return zipped.encodeBase64()
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top