下面的代码试图简化使用EXIficient执行 EXI 压缩和解压缩所需的设置
class ExiCompressionUtils {
static Transformer transformer = TransformerFactory.newInstance().newTransformer()
static byte[] compress(String xml) {
ByteArrayOutputStream exiOS = new ByteArrayOutputStream()
EXIResult exiResult = new EXIResult(outputStream : exiOS)
XMLReader xmlReader = XMLReaderFactory.createXMLReader()
xmlReader.contentHandler = exiResult.handler
xmlReader.parse(new InputSource(new StringReader(xml)))
def compressed = exiOS.toByteArray()
exiOS.close()
return compressed
}
static String extract(byte[] compressed) {
SAXSource exiSource = new SAXSource(new InputSource(new ByteArrayInputStream(compressed)))
exiSource.setXMLReader(exiSource.reader)
ByteArrayOutputStream exiOS = new ByteArrayOutputStream()
transformer.transform(exiSource, new StreamResult(exiOS)) // fails here
def extracted = exiOS.toString()
exiOS.close()
return compressed
}
}
下面的测试失败了ERROR: 'Invalid byte 1 of 1-byte UTF-8 sequence.'
@Test
void testExiCompression() {
def xml = '<Root><Child id="1">Text</Child><EmptyTag/></Root>'
def compressed = ExiCompressionUtils.compress(xml)
assert ExiCompressionUtils.extract(compressed) == xml
}
那里有任何编码专家可以深入了解这一点吗?