Я пытаюсь распаковать и декодировать (base64) строку из gZip.Я написал один класс для того же и тестовый код.Я получаю
Exception in thread "main" java.lang.IndexOutOfBoundsException
на линии
while ((readByte = gzipIS.read(gzipByteBuffer)) != -1) byteOS.write(
базовый код:
import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStreamReader
import java.io.UnsupportedEncodingException
import java.nio.charset.StandardCharsets
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import org.apache.commons.codec.binary.Base64
import org.apache.commons.io.IOUtils
class ZipUtilities {
def unzipCCBRsponse(inputB64: String): String = {
val bDecodeBase64: Array[Byte] = Base64.decodeBase64(inputB64)
var zipInputStream: GZIPInputStream = null
try {
zipInputStream = new GZIPInputStream(
new ByteArrayInputStream(bDecodeBase64, 4, bDecodeBase64.length - 4))
val inputStreamReader: InputStreamReader =
new InputStreamReader(zipInputStream, StandardCharsets.UTF_8)
val bufferedReader: BufferedReader = new BufferedReader(
inputStreamReader)
val output: StringBuilder = new StringBuilder()
var line: String = null
while ((line = bufferedReader.readLine()) != null) output.append(line)
println("Output String Length: " + output.length)
bufferedReader.close()
output.toString
} catch {
case e: IOException => e.printStackTrace()
}
null
}
def decodeBase64(b64EncodedString: String): String = {
var bDecodeBase64: Array[Byte] = null
try {
bDecodeBase64 =
Base64.decodeBase64(b64EncodedString.getBytes("ISO-8859-1"))
new String(bDecodeBase64)
} catch {
case e: UnsupportedEncodingException => e.printStackTrace()
}
null
}
def decodeFromGzip(input: String): String = {
var output: String = null
if (input != null && !input.isEmpty) {
try {
var readByte: Int = 0
val gzipByteBuffer: Array[Byte] = Array.ofDim[Byte](2048)
val gzipIS: GZIPInputStream = new GZIPInputStream(
new ByteArrayInputStream(Base64.decodeBase64(input)))
val byteOS: ByteArrayOutputStream = new ByteArrayOutputStream()
while ((readByte = gzipIS.read(gzipByteBuffer)) != -1) byteOS.write(
gzipByteBuffer,
0,
readByte)
byteOS.close()
output = new String(byteOS.toByteArray())
} catch {
case e: IOException => e.printStackTrace()
}
}
output
}
}
Тестовый код:
object ZipTest {
def main(args: Array[String]): Unit = {
val b64: String =
"H4sIAAAAAAAAAO2dW1PbOBTH3/spNHkvgXYvLVPoCFlJtNiSR5IT8sRkUxeYJQmThMJ++5Xt3LjNNsdwVprNC8N4fPz/2dblXGTly9f70TX5kU9nV5PxUeNgb79B8vFw8u1qfHHUuJ1"
val util: ZipUtilities = new ZipUtilities()
println(util.decodeFromGzip(b64).replaceAll("\n", ""))
}
}