폴더의 압축을 풀고 특정 폴더를 선택하고 다시 압축

Mohit Saini :

나는 - 그것을 압축을 해제 할 때 나는 구조를 다음 한 하나 개의 압축 폴더 (예를 test.zip)가

WebContent/config/somefiles
WebContent/css/somefile
Webcontent/fonts/somefiles
Webcontent/js/somefiles
WebContent/index.html

지금은이 구조에서의 WebContent를 제거해야합니다. 내 최종 압축 해제 파일이 있어야합니다 config, css,js그리고 index.html루트 위치에서.

내가있는 WebContent에 존재하는 모든 파일을 압축 다시 다음의 WebContent 폴더 우회 주먹 압축 해제 test.zip에 대한 효율적인 자바 코드를 알고 주시기 바랍니다.

미리 감사드립니다!

토마스 Bitonti :

좋은 일이 당신의 도구 키트에 가지고, 그래서 이것은 일반적인 패턴 / 활동이다.

아래의 코드를 참조하십시오. 또는 전송할 수없는 항목의 드라이브 선택에 필요에 따라 사용자 정의 할 수있는 '선택'방법이있다 :

private static boolean select(String entryName) {
    return true; // Customize me
}

주 디렉토리 예를 들어 디렉토리 내 파일에 대한 디렉토리 자체 (예를 들어, "META-INF /"에 대한 항목뿐만 아니라 항목을 (가질 수, 'META-INF / MANIFEST.MF'). 디렉토리를 건너 뛰는 항목은 디렉토리에있는 항목을 생략하지 않습니다.

참고 또한,이 디스크에 대한 압축 풀기를 피할 수 있습니다. 즉, 실행 시간에 많은 추가하기 때문에, 피해야하는 것입니다. (그러나 전체 항목이 메모리에로드되지 않습니다 또한 참고로만 데이터의 단일 bufferfull 메모리에 있나이다.)

코드를 가정하면, 사용은 'transfer.jar'에있다 :

사용법 : sample.transfer.TransferSample inputPath outputPath

예를 들어,에이 도구를 실행하는 자신의 병입니다 :

java -classpath transfer.jar sample.transfer.TransferSample transfer.jar transfer.jar.out

Transfer from [ transfer.jar ]
Transfer to [ transfer.jar.out ]
Transfer from [ c:\dev\transfer\transfer.jar ] (absolute path)
Transfer to [ c:\dev\transfer\transfer.jar.out ] (absolute path)
Entry [ META-INF/MANIFEST.MF ]: Selected
Transferred [ 25 ] bytes
Entry [ sample/ ]: Selected
Entry [ sample/transfer/ ]: Selected
Entry [ sample/transfer/TransferSample.class ]: Selected
Transferred [ 4061 ] bytes
Entry [ sample/transfer/TransferSample.java ]: Selected
Transferred [ 3320 ] bytes
Transfer Success

여기에 코드입니다 :

package sample.transfer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class TransferSample {

    public static void main(String args[]) {
        if ( args.length < 2 ) {
            System.out.println("Usage: " + TransferSample.class.getName() + " inputPath outputPath");
            return;
        }

        String inputPath = args[0];
        String outputPath = args[1];

        System.out.println("Transfer from [ " + inputPath + " ]");
        System.out.println("Transfer to [ " + outputPath + " ]");

        File inputFile = new File(inputPath);
        File outputFile = new File(outputPath);

        System.out.println("Transfer from [ " + inputFile.getAbsolutePath() + " ] (absolute path)");
        System.out.println("Transfer to [ " + outputFile.getAbsolutePath() + " ] (absolute path)");

        try ( InputStream inputStream = new FileInputStream(inputFile) ) { // throws IOException
            try ( OutputStream outputStream = new FileOutputStream(outputFile) ) { // throws IOException
                transfer(inputStream, outputStream);
                System.out.println("Transfer Success");
            }
        } catch ( IOException e ) {
            System.err.println("Transfer Failure");
            e.printStackTrace(System.err);
        }
    }

    // All static to keep the code simpler.

    public static void transfer(InputStream inputStream, OutputStream outputStream) throws IOException {
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        try {
            transfer(zipInputStream, zipOutputStream); // throws IOException
        } finally {
            zipOutputStream.finish(); // throws IOException
        }
    }

    private static final int BUFFER_SIZE = 64 * 1024;

    private static boolean select(String entryName) {
        return true; // Customize me
    }

    public static void transfer(ZipInputStream zipInputStream, ZipOutputStream zipOutputStream) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE]; // Single buffer for all transfers

        ZipEntry inputEntry;
        while ( (inputEntry = zipInputStream.getNextEntry()) != null ) {
            String entryName = inputEntry.getName();

            if ( !select(entryName) ) {
                System.out.println("Entry [ " + entryName + " ]: Not selected");
                continue;
            } else {
                System.out.println("Entry [ " + entryName + " ]: Selected");
            }

            zipOutputStream.putNextEntry(inputEntry); // throws IOException

            if ( !inputEntry.isDirectory() ) {
                long bytesTransferred = transfer(zipInputStream, zipOutputStream, buffer); // throws IOException
                System.out.println("Transferred [ " + bytesTransferred + " ] bytes");

                zipOutputStream.closeEntry(); // throws IOException
            }
        }
    }

    private static long transfer(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException {
        long totalBytesRead = 0L;

        int bytesRead = 0;
        while ( (bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1 ) { // throws IOEXception
            totalBytesRead += bytesRead;
            outputStream.write(buffer, 0, bytesRead);
        }

        return totalBytesRead;
    }
}

추천

출처http://10.200.1.11:23101/article/api/json?id=400914&siteId=1