투케이2K

807. (Android/Java) [유틸 파일] createZipFile : zip 파일 생성 수행 본문

Android

807. (Android/Java) [유틸 파일] createZipFile : zip 파일 생성 수행

투케이2K 2024. 6. 14. 16:39
반응형

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Java / Kotlin

 

[소스 코드]

 

    // -----------------------------------------------------------------------------------------
    // TODO [SEARCH FAST] : [Observable] : createZipFile : zip 파일 생성 수행
    // -----------------------------------------------------------------------------------------
    // TODO [호출 방법 소스 코드]
    // -----------------------------------------------------------------------------------------
    /*
    try {

        // [공용 저장소 다운로드 폴더 >> 특정 폴더 지정]
        String downLoadfilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        downLoadfilePath += "/LOG_SAVE_FOLDER/";

        // [생성할 Zip 파일 명칭]
        String zipPath = downLoadfilePath + "output.zip";

        // [압축할 대상의 자식 파일 명칭]
        List<String> filePaths = Arrays.asList(
                downLoadfilePath + "APP_CRASH_LOG.txt",
                downLoadfilePath + "APP_USE_LOG.txt"
        );

        C_App.createZipFile(A_Intro.this, zipPath, filePaths)
                .subscribeOn(AndroidSchedulers.mainThread()) // [Observable (생성자) 로직을 IO 스레드에서 실행 : 백그라운드]
                .observeOn(Schedulers.io()) // [Observer (관찰자) 로직을 메인 스레드에서 실행]
                .subscribe(new Observer<Boolean>() { // [Observable.create 타입 지정]
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }
                    @Override
                    public void onNext(@NonNull Boolean value) {
                        S_Log._W_("Zip 파일 생성 결과 :: " + String.valueOf(value), null);
                    }
                    @Override
                    public void onError(@NonNull Throwable e) {
                        S_Log._E_("Zip 파일 생성 에러 :: " + String.valueOf(e.getMessage()), null);
                    }
                    @Override
                    public void onComplete() {
                    }
                });
    }
    catch (Exception e){
        e.printStackTrace();
    }
    */
    // -----------------------------------------------------------------------------------------
    public static Observable<Boolean> createZipFile(Context mContext, String zipPath, List<String> childList){

        // [로직 처리 실시]
        return Observable.create(subscriber -> {

            /**
             * // -----------------------------------------
             * [createZipFile 메소드 설명]
             * // -----------------------------------------
             * 1. zip 파일 생성 수행
             * // -----------------------------------------
             * 2. 리턴 데이터 : zip 파일 생성 성공 시 true / 문제 발생 시 false
             * // -----------------------------------------
             * 3. 추가로 외부 저장소에 파일 읽기 및 쓰기를 위해서 Manifest 권한 필요 및 인텐트 이동 수행
             *
             * 권한 : <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
             *
             * 인텐트 이동 : Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
             * // -----------------------------------------
             * 4. 참고 설명 [1] :
             *
             * MANAGE_EXTERNAL_STORAGE 권한을 추가 시 마켓에 특정 용도로 사용하는 앱 목적을 밝혀야합니다
             * (앱 등록 및 업데이트 리젝 될 수 있습니다)
             *
             * 외부 저장소 경로 : /storage/emulated/0
             * // -----------------------------------------
             * 5. 참고 설명 [2] :
             *
             * - 안드로이드 하위 (os 11 이하) 인 경우 외부 저장소 읽기 , 쓰기 권한 부여 필요
             * - 안드로이드 상위 (os 11 이상) 인 경우 AndroidManifest.xml 파일에서 MANAGE_EXTERNAL_STORAGE 권한 부여 수행
             * - 안드로이드 외부 저장소 접근 권한이 없는 경우는 앱 내부 캐시 저장소에 파일 저장 후 zip 파일 생성 수행
             * // -----------------------------------------
             * */

            S_Log._D_("Zip 파일 생성 수행", new String[]{"zipPath :: " + String.valueOf(zipPath), "childList :: " + String.valueOf(childList)});

            try {

                // [인풋 데이터 방어 로직 작성]
                if (C_Util.stringNotNull(zipPath) == true && childList != null && childList.size()>0){

                    // [안드로이드 버전 제한]
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // [오레오 이상]

                        // [반복문을 수행하면서 자식 리스트 추가 실시]
                        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPath))) { // [Zip 파일 만들기 정의]
                            for (String filePath : childList) {
                                File fileToZip = new File(filePath); // [자식 File 확인]
                                zipOut.putNextEntry(new ZipEntry(fileToZip.getName())); // [Zip 파일에 자식 추가]
                                Files.copy(fileToZip.toPath(), zipOut); // [Zip 파일 경로로 자식 복사]
                            }
                            S_Log._W_("Zip 압축 파일 생성 성공", null);

                            // [리턴 반환]
                            subscriber.onNext(true);
                            subscriber.onComplete();
                        }

                    }
                    else {
                        subscriber.onError(new Throwable("[Error] : Android Version Issue"));
                        subscriber.onComplete();
                    }

                }
                else {
                    subscriber.onError(new Throwable("[Error] : Input Data Is Null"));
                    subscriber.onComplete();
                }

            } catch (final Exception e){
                e.printStackTrace();

                try {
                    subscriber.onError(new Throwable("[Exception] : [catch] : "+String.valueOf(e.toString())));
                    subscriber.onComplete();
                }
                catch (Exception ex){
                    ex.printStackTrace();
                }
            }

        });
    }

 

반응형
Comments