我正在尝试从gZip解压缩和解码(base64)字符串。 我为同一类和一个测试代码编写了一个类。 我正在
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", ""))
}
}
答案 0 :(得分:1)
在Scala中,赋值(readByte = gzipIS.read(gzipByteBuffer)
)返回Unit
,并且由于类型Unit
的值永远不会等于-1
(或任何Int
值) ,则您的while
循环实际上是无限的。
编译器应该已经警告您:
警告:使用“!=”比较Unit和Int类型的值将始终为true
注意:在惯用的Scala代码中,您很少看到null
或var
。几乎不需要。