我尝试对 XML 进行 Gzip 和 Base64 编码,然后保存在数据库中。
代码:
public static Base64OutputStream compressAndEncode(String file) throws IOException, URISyntaxException {
String filePath = getAbsoluteFilePath("test.xml");
String fileContent = Files.readString(Path.of(filePath), StandardCharsets.UTF_8);
Base64OutputStream gzipBase64 = fileGzipAndBase64(fileContent);
LOG.info("gzipBase64: " + gzipBase64.toString());
return gzipBase64;
}
public static Base64OutputStream fileGzipAndBase64(String fileContent) throws IOException {
try {
Base64OutputStream b64os = new Base64OutputStream(System.out);
GZIPOutputStream gzip = new GZIPOutputStream(b64os);
gzip.write(fileContent.getBytes("UTF-8"));
gzip.close();
b64os.close();
return b64os;
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
Base64OutputStream data = TestResourceHelper.compressAndEncode1(paymentFile);
sql = "insert into file (xml-content) values(decode('" + data + "', 'base64'))";
但是在数据库插入步骤中我收到以下错误
ERROR: invalid symbol "." found while decoding base64 sequence
但是,如果我使用硬编码字符串作为
data = "H4sIAAAAAAA..xftH+CWV0apGQAA"
它可以工作
所以我猜想
compressAndEncode()
方法中的输出存在一些问题
问题是我错过了 ByteArrayOutputStream 到 ByteArray 的转换
public static Base64OutputStream fileGzipAndBase64(String fileContent) 抛出 IOException {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream(); //** new-line ***
Base64OutputStream b64os = new Base64OutputStream(System.out);
GZIPOutputStream gzip = new GZIPOutputStream(b64os);
gzip.write(fileContent.getBytes("UTF-8"));
gzip.close();
b64os.close();
String base64 = new String(os.toByteArray(), "UTF-8"); //** new-line ***
return base64;
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}