구현하게된 계기 및 이유

현재 회사에서 금융권에 파견을 가있는 상황인데 각 증권사로 보내는 PDF파일들을 Tar로 묶어서 전송하라는 요청이 왔습니다.

아쉽게도 Tar로 묶어서 전송을 하라는 이유는 정확히 듣지 못하고 요청만 들어온 상황이라 구현을 하게 되었습니다.

저는 리눅스 환경에서 파일을 압축해서 전송하기 위해서 Tar 압축 형식을 사용한 것이라 생각했습니다.

윈도우에서는 zip파일형식이 있다면 리눅스는 Tar파일형식이 있다는것을 알게 되었습니다.

 

리눅스에서 Tar 명령어를 사용해 압축이 가능하지만 서버쪽에서 자바 코드로 구현을 해야 했기 때문에 자바로 구현했습니다.

 

 

 

사용한 라이브러리

 

 

 

소스코드

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.IOUtils;

import java.io.*;

public class CompressToTar {

	// 타르 압축 함수를 실행 할 메인 메서드
    public static void main(String[] args) throws Exception {
        compressToTar();
    }


	
    private static void compressToTar() throws Exception {
		
        // 타르 파일 생성 경로를 입력해주세요.
        String tarOutputPath = "타르파일 생성 경로";

        try {
        	// 찹축할 파일이 있는 경로를 입력해주세요.
            File inputFilePath = new File("압축할 파일이 있는 경로");

			// 필터를 통해 원하는 파일 형식 및 파일들만 배열로 파일리스트로 가져옵니다.
            File[] pdfFileArray = inputFilePath.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.endsWith("압축할 파일들의 파일명 패턴");
                }
            });


             if (pdfFileArray.length != 0) {
             
             	// 생설할 타르 파일명과 .tar 확장자를 꼭 붙여주세요.
                File tarOutputFile = new File(tarOutputPath, "test.tar");

                FileOutputStream fOut = new FileOutputStream(tarOutputFile);
                BufferedOutputStream bOut = new BufferedOutputStream(fOut);
                TarArchiveOutputStream tOut = new TarArchiveOutputStream(bOut);


                for (File file : pdfFileArray) {
                    TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(file, file.getName());
                    tarArchiveEntry.setModTime(0);
                    tarArchiveEntry.setSize(file.length());

					// tar아웃풋 스트림에 tar아카이브 엔트리 put
                    tOut.putArchiveEntry(tarArchiveEntry);
                    
                    // tar아웃풋 스트림을 통해 해당 파일 생성(write)
                    // -> 이때 IOUtils를 사용해서 해당 파일을 ByteArray로 변환합니다.
                    tOut.write(IOUtils.toByteArray(new FileInputStream(file)));

                    tOut.closeArchiveEntry();
                }

                tOut.flush();
                tOut.finish();
                tOut.close();
                bOut.close();
                fOut.close();
            } else {
                System.out.println("해당 폴더에 압축할 파일이 없습니다.");
            }

        } catch (Exception e) {
            System.out.println("compress 에러 발생: " + e);
            throw new Exception(e);
        }

    }
}

* 위에 작성된 코드는 예시입니다. 참고만 하시고 더 견고한 코드를 작성하시는걸 권장드립니다.

 

 

 

구현하면서 느낀점

구현하는 것은 크게 문제가 되지 않는 기능이였습니다.

하지만 금융권 개발 환경이 생각보다 낮은 자바 버전을 사용해서, 호환이 되는 라이브러리를 찾는게 시간이 꽤 걸렸습니다.

이번에 구현하면서 이런 안좋은 개발환경에서도 차선책이 존재한다는 것을 느꼈습니다.

많은 사람들이 사용하는 검증된 라이브러리가 검색하면 엄청 많이 나오는 라이브러리를 사용하지 못했지만,

계속 검색해보면 해당 라이브러리와 비슷한 기능을 하는 것이 있다는 것을 체감했습니다.

 

 

 

반응형

+ Recent posts