[kotlin] 파일의 압축 여부 확인하는 방법
Kotlin을 사용하여 파일이 압축되었는지 여부를 확인하는 방법을 알아보겠습니다. Kotlin은 Java와 호환되므로 Java의 기능을 활용할 수 있습니다.
Zip 파일의 압축 여부 확인
import java.util.zip.ZipFile
fun isZipFile(filePath: String): Boolean {
val zipFile = ZipFile(filePath)
return zipFile.entries().hasMoreElements()
}
fun main() {
val filePath = "path/to/your/zip/file.zip"
val isZip = isZipFile(filePath)
if (isZip) {
println("The file is a zip file.")
} else {
println("The file is not a zip file.")
}
}
위의 예시 코드는 ZipFile
클래스를 사용하여 주어진 파일이 zip 파일인지 확인합니다. entries()
메서드를 호출하여 파일이 압축되었는지 여부를 확인할 수 있습니다.
Gzip 파일의 압축 여부 확인
import java.io.BufferedInputStream
import java.io.FileInputStream
import java.util.zip.GZIPInputStream
fun isGzipFile(filePath: String): Boolean {
val inputStream = BufferedInputStream(FileInputStream(filePath))
return try {
GZIPInputStream(inputStream)
true
} catch (ex: Exception) {
false
} finally {
inputStream.close()
}
}
fun main() {
val filePath = "path/to/your/gzip/file.gz"
val isGzip = isGzipFile(filePath)
if (isGzip) {
println("The file is a gzip file.")
} else {
println("The file is not a gzip file.")
}
}
위의 예시 코드는 GZIPInputStream
클래스를 사용하여 주어진 파일이 gzip 파일인지 확인합니다. 파일을 열고 GZIPInputStream
을 생성하여 예외를 처리하는 방식으로 압축 여부를 확인합니다.
이러한 방법을 사용하여 Kotlin에서 파일이 압축되었는지 여부를 간단하게 확인할 수 있습니다.