03.업/01.자바

java로 여러 파일들 zip파일로 압축 및 압출 풀기

봄날의차 2023. 6. 22. 13:09

윈도우에서 파일을 웹루트이외의 다른 디렉토리에 업로드 다운로드시에 해당 폴더를

server.xml에서 context로 지정해서 참조시킨다.

<Context docBase="C:\data\***\stp2svg\" path="/data" reloadable="true" />

 

>> 압축하기<<

            //3.[svg, log] 압축하기
            filePaths = new ArrayList<String>();
            filePaths.add(svgFile); //C:\***\data\stp2svg\20230620114531114_C0000101-001-연결종합평면도.svg
            filePaths.add(logFile); //C:\***\data\stp2svg\20230620114531114_C0000101-001-연결종합평면도.log

//            int fidx = 0;
            Path tmpPath = null;
            String zipFileNm = CommonUtils.leftOfR(tempSvgFile, ".") + ".zip";
            File zipFile = new File(SvgDirectory, zipFileNm);
            System.out.println("zipFileNm1:"+zipFileNm); //C:\***\data\stp2svg\20230620114531114_C0000101-001-연결종합평면도.zip

            ZipOutputStream zipOutputStream = null;
            FileInputStream fileInputStream = null;
            byte[] buf = new byte[MAX_SIZE];

            try{

                zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));

                for(String fNm:filePaths){
                	System.out.println("fNm:"+fNm);
                	tmpPath = Paths.get(fNm);
            		System.out.println("Path tmpPath = Paths.get(fNm)");
            		System.out.println(tmpPath);
            		System.out.println("Parent:"+tmpPath.getParent());

            		fileInputStream = new FileInputStream(tmpPath.toFile());
            		zipOutputStream.putNextEntry(new ZipEntry(tmpPath.toFile().getName()));

            		int length = 0;
            		while(((length=fileInputStream.read(buf)) > 0)){
            			zipOutputStream.write(buf, 0, length);
            		}
            		zipOutputStream.closeEntry();
            		fileInputStream.close();
                }
                zipOutputStream.close();
                System.out.println("압축  파일 생성 성공 ");

            } catch(IOException e) {
            	e.printStackTrace();
            	System.out.println(e.getMessage());
            } finally {
            	try{
            	zipOutputStream.closeEntry();
            	zipOutputStream.close();
            	fileInputStream.close();
            	} catch(IOException e){
                	System.out.println(e.getMessage());
            	}
            }

 

>>압축풀기<<

        //압축풀기
        FileInputStream zipFileInputStream = null;
        FileOutputStream zipFileOutputStream = null;
        ZipInputStream zis = null;

        ...
        
            // 압축해제
            // 파일 정상적으로 압축이 해제가 되어는가.
            boolean isUnZipChk = false;
        	System.out.println(zipName); // C:\...\data\stp2svg\20230620164433237_C0000101-001-연결종합평면도.zip
        	String zipUnzipPath = CommonUtils.leftOfR(zipName, File.separator); //압축해제할 폴더경로 
        	System.out.println("zipUnzipPath:"+zipUnzipPath);

        	//fileSvgPath + 마지막 폴더
//        	CommonUtils.makePath(zipUnzipPath);

        	File zipFile = new File(zipName);
        	System.out.println("zipFile zipName : " + zipName);

        	FileInputStream fis = null;
        	ZipEntry zipEntry = null;
// try
        	try{
	        	// zipFoleName으로 폴더만들기...

//	        	resSvgName = CommonUtils.rightOfR(zipName, ".") + ".svg" ;
//	        	resSvgLogName = CommonUtils.rightOfR(zipName, ".") + ".log" ;

	        	// 파일 스트림
	        	fis = new FileInputStream(zipFile);
	        	// Zip 파일 스트림
	        	zis = new ZipInputStream(fis, Charset.forName("UTF-8"));

	        	// 압축되어 있는 ZIP 파일의 목록 조회
	        	while( (zipEntry = zis.getNextEntry()) != null ){
	        		String fn = zipEntry.getName();
	        		System.out.println("fileSvgPath => " + fileSvgPath);
	        		System.out.println("filename(zipentry.getName()) => " + fn);
	        		if(CommonUtils.rightOfR(fn, ".").toLowerCase().equals("svg")){
	        			resSvgName = fn;
	        		}else if(CommonUtils.rightOfR(fn, ".").toLowerCase().equals("log")){
	        			resSvgLogName = fn;
	        		}
	        		File file = new File(fileSvgPath, fn);

	        		//entiry가 폴더면 폴더 생성
	        		if(zipEntry.isDirectory()){
	        			file.mkdirs();
	        		}else{
	        			//파일이면 파일 만들기
	        			System.out.println("zipentry가 파일입니다.");
	        			try{
	        				CommonUtils.createFile(file, zis);
	        			}catch(Throwable e){
	        				e.printStackTrace();
	        			}
	        		}
	        	}
	        	isUnZipChk = true;
                
    		} catch (Exception e) {
    			isUnZipChk = false;
    		} finally {
    			if (zis != null) {
    				try {
    					zis.close();
    				} catch (IOException e) {
    				}
    			}
    			if (fis != null) {
    				try {
    					fis.close();
    				} catch (IOException e) {
    				}
    			}
    		}
        	//unzip end
            
            
            
    		// zip 파일 삭제
        	if(isUnZipChk){
        		Path zipFilePath = Paths.get(zipName);
        		try{
        			Files.deleteIfExists(zipFilePath);
        		} catch (IOException e){
        			System.out.println(e.getMessage());
        			e.printStackTrace();
        		}
        	}

 

>> createFile<<

    public static void createFile(File file, ZipInputStream zis) throws Throwable {
    	System.out.println("createFile");
    	// 디렉토리 확인
    	File parentDir = new File(file.getParent());
    	System.out.println("parentDir : "+parentDir);
    	// 디렉토리가 없으면 생성하자
    	if(!parentDir.exists()){
    		parentDir.mkdirs();
    	}

    	// 파일 스트림 선언
    	FileOutputStream fos = null;
    	try{
    		fos = new FileOutputStream(file);
    		byte[] buffer = new byte[256];
    		int size = 0;
    		// Zip스트림으로부터 byte뽑아내기
    		while ((size = zis.read(buffer)) > 0) {
    			// byte로 파일 만들기
    			fos.write(buffer, 0, size);
    		}
    	}catch(Throwable e){
    		System.out.println(e.getMessage());
    	}finally{
    		if(fos != null){
    			try{
    				fos.close();
    			}catch (IOException e) {
    			}
    		}
    	}
    }