我正在尝试让 Tomcat 将 servlet 内容写为 bzip2 文件(可能是愚蠢的要求,但对于某些集成工作显然是必要的)。我正在使用 Spring 框架,所以它位于 AbstractController 中。
我正在使用来自 http://www.kohsuke.org/bzip2/的 bzip2 库
我可以很好地将内容 bzip 压缩,但是当文件被写出时,它似乎包含一堆元数据并且无法识别为 bzip2 文件。
这就是我正在做的
// get the contents of my file as a byte array
byte[] fileData = file.getStoredFile();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//create a bzip2 output stream to the byte output and write the file data to it
CBZip2OutputStream bzip = null;
try {
bzip = new CBZip2OutputStream(baos);
bzip.write(fileData, 0, fileData.length);
bzip.close();
} catch (IOException ex) {
ex.printStackTrace();
}
byte[] bzippedOutput = baos.toByteArray();
System.out.println("bzipcompress_output:\t" + bzippedOutput.length);
//now write the byte output to the servlet output
//setting content disposition means the file is downloaded rather than displayed
int outputLength = bzippedOutput.length;
String fileName = file.getFileIdentifier();
response.setBufferSize(outputLength);
response.setContentLength(outputLength);
response.setContentType("application/x-bzip2");
response.setHeader("Content-Disposition",
"attachment; filename="+fileName+";)");
这是从 Spring abstractcontroller 中的以下方法调用的
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception
我用不同的方法尝试了一些方法,包括直接写入 ServletOutput,但我很困惑,在网上找不到任何/很多示例。
以前遇到过这种情况的任何人的任何建议都将不胜感激。替代库/方法很好,但不幸的是它必须是 bzip2'd。