[android] 안드로이드 파일 시스템과 파일 압축 해제 방법

안드로이드 앱 개발 시 파일 시스템을 다루는 것은 중요한 부분입니다. 안드로이드에서 파일을 읽고 쓰며, 파일을 압축하고 해제하는 방법을 다루어봅시다.

안드로이드 파일 시스템

안드로이드 앱에서 파일 시스템에 접근하려면 AndroidManifest.xml 파일에 권한을 추가해야 합니다. 아래와 같이 권한을 추가할 수 있습니다.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

또한, 안드로이드에서 파일 시스템에는 내부 저장소(internal storage)와 외부 저장소(external storage)가 있습니다. 내부 저장소는 다른 앱과 공유되지 않는 앱 전용 영역이고, 외부 저장소는 사용자가 읽고 쓸 수 있고 필요한 앱끼리 파일을 공유할 수 있습니다.

내부 저장소에 파일을 쓰고 읽으려면 ContextopenFileOutputopenFileInput 메서드를 사용할 수 있고, 외부 저장소에 파일을 쓰고 읽으려면 Environment.getExternalStorageDirectory() 메서드를 사용하여 외부 저장소의 경로를 얻을 수 있습니다.

파일 압축 해제

Java에서 파일을 압축하고 압축을 해제하기 위해 java.util.zip 패키지를 사용할 수 있습니다.

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ZipHelper {
    public void unzip(String zipFile, String extractionFolder) throws IOException {
        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            String fileName = zipEntry.getName();
            File newFile = new File(extractionFolder + File.separator + fileName);
            new File(newFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            zipEntry = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
    }
}

위의 코드는 ZipHelper 클래스에 unzip 메서드를 사용하여 압축 파일을 푸는 기능을 구현한 예시입니다.

이제 안드로이드에서는 이와 같은 방법을 활용하여 파일 시스템을 다루고 파일을 압축 해제할 수 있습니다.


참고 문헌: