본문으로 바로가기

Java 파일 압축 및 특정 파일 리스트 추출

category Backend/Java 2020. 2. 21. 11:26

Java 파일 압축 및 특정 파일 리스트 추출


        // 샘플 압축파일
        String zipFile = "D:/zipTemp/temp.zip";
        String zipTempPath = "D:/Temp/"// Temp 경로 로컬
        
        // 중복자 제외를 위한 timestamp
        Calendar cal = Calendar.getInstance();
        
        // 다운로드 이름
        String downloadFileName = "첨부파일"// 첨부파일
        
        // 반복문 시작
        
        for(int i=0; i<mFile.keySize(); i++) {
            // 사용자 압축파일명
            String userZipFileName = "첨부파일" + cal.getTimeInMillis() + ".zip"// timstamp로도 중복 제거가안된다면 파일명에 추가 혹은 대체로 다른 값을 넣어준다 (일련번호 추천)
            
            // 사용자 일련번호
            String seqNo = mFile.getString("seqNo", i);
            
            // 이전과 다음을 비교하는 값
            Boolean chkBool = false;
            
            // 파일 리스트 생성
            List<String> sourceFiles = new ArrayList<String>();
            
            while(true) { // 일단 무한 반복
                
                // 다음 파일 소유자가 현재와 다르다면 현재까지 생성된 리스트를 압축
                if (i + 1< mFile.keySize()) {
                    if (!seqNo.equals(mFile.getString("seqNo", i + 1))) {
                        chkBool = true;
                    }
                } else {
                    chkBool = true// 끝
                }
                
                sourceFiles.add(mFile.getString("filePath", i));
                
                if (chkBool) {
                    break;
                }
                
                i++;
            }
            
            // 파일 생성된 리스트로 압축파일 생성
            // ZipOutputStream을 FileOutputStream 으로 감쌈
            FileOutputStream fout = new FileOutputStream(userZipFileName);
            ZipOutputStream zout = new ZipOutputStream(fout);
            
            for(int j=0; j < sourceFiles.size(); j++){
                // 본래 파일명 유지, 경로제외 파일압축을 위해 new File로 
                ZipEntry zipEntry = new ZipEntry(new File(sourceFiles.get(j)).getName());
                zout.putNextEntry(zipEntry);
 
                FileInputStream fin = new FileInputStream(sourceFiles.get(j));
                byte[] buffer = new byte[1024];
                int length;
 
                // input file을 1024바이트로 읽음, zip stream에 읽은 바이트를 씀
                while((length = fin.read(buffer)) > 0){
                    zout.write(buffer, 0length);
                }
 
                zout.closeEntry();
                fin.close();
            }
 
            zout.close();
        }
        
        // 반복문 끝
        
        // Temp 경로에 특정 패턴으로 된 목록 추출
        File path = new File(zipTempPath);
        final String pattern = mFile.getString("aTitle"0+ "_" + aNo; 
        
        // 파일필터설정
        FilenameFilter filter = new FilenameFilter() {
             public boolean accept(File dir, String name) //지정된 디렉토리, 파일명
             {
                  return name.startsWith(pattern); // RC로 시작되는 모든 파일
             }
        };
        
        // 필터된 목록
        String[] fileList = path.list(filter);
        
        
        // 파일 리스트 생성
        List<String> sourceFiles2 = new ArrayList<String>();
        
        for (int k=0; k<fileList.length; k++) {
//             System.out.println("fileList >>> " + fileList[k]);
            sourceFiles2.add(zipTempPath + fileList[k]);
        }
        
        // 필터된 목록 재압축
         // 파일 생성된 리스트로 압축파일 생성
        // ZipOutputStream을 FileOutputStream 으로 감쌈
        FileOutputStream fout = new FileOutputStream(zipFile);
        ZipOutputStream zout = new ZipOutputStream(fout);
        
        for(int j=0; j < sourceFiles2.size(); j++){
            // 본래 파일명 유지, 경로제외 파일압축을 위해 new File로 
            ZipEntry zipEntry = new ZipEntry(new File(sourceFiles2.get(j)).getName());
            zout.putNextEntry(zipEntry);
 
            FileInputStream fin = new FileInputStream(sourceFiles2.get(j));
            byte[] buffer = new byte[1024];
            int length;
 
            // input file을 1024바이트로 읽음, zip stream에 읽은 바이트를 씀
            while((length = fin.read(buffer)) > 0){
                zout.write(buffer, 0length);
            }
 
            zout.closeEntry();
            fin.close();
        }
 
        zout.close();
        
        
        out.clear();
        out = pageContext.pushBody();
        
        response.reset();
        // 파일형식 정보 설정
        String header = request.getHeader("User-Agent");
        response.setContentType("application/zip");
        if (header.contains("MSIE"|| header.contains("Trident")) {
            downloadFileName = URLEncoder.encode(downloadFileName,"UTF-8").replaceAll("\\+""%20");
            response.setHeader("Content-Disposition""attachment;filename=" + downloadFileName + ".zip;");
        } else {
            downloadFileName = new String(downloadFileName.getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition""attachment; filename=\"" + downloadFileName + "\".zip");
        }
 
        fis = new FileInputStream(zipFile);
        bis = new BufferedInputStream(fis);
        so = response.getOutputStream();
        bos = new BufferedOutputStream(so);
 
        byte[] data=new byte[2048];
        int input=0;
 
        while((input=bis.read(data))!=-1){
            bos.write(data,0,input);
            bos.flush();
        }
 
    }catch(Exception e){
        Log.log(Log.ERROR, "ERROR!!");
        out.print(e.getMessage());
        e.printStackTrace();
        response.sendError(500, StringUtil.toEnglish(e.getMessage()));
    }finally{
        if(bos!=null) bos.close();
        if(bis!=null) bis.close();
        if(so!=null) so.close();
        if(fis!=null) fis.close();
    }
%>




'Backend > Java' 카테고리의 다른 글

URL 호출  (0) 2020.07.07
IP 및 모바일 체크  (0) 2020.03.23
Struts2 textfield Null 인 경우  (0) 2020.02.17
게시판 번호 역순 출력  (0) 2019.12.12
파일 다운로드 기본  (0) 2019.11.11