数据流直接生成zip压缩包(文件主要是对csv格式)

来源:互联网 发布:node需要nginx吗 编辑:程序博客网 时间:2024/05/22 05:00

最近在做爬虫项目的时候遇到了点问题,就是从别人的服务器请求后获得的响应byte[]数据,并不想在本地服务器进行转存后再下载,所以就尝试了直接生成下载包。

public void export_1 (HttpServletResponse response, HttpServletRequest request) {//相关网络请求及响应操作省略此处{//dosomething}//定义打出的压缩包的名称String zipName = "测试";//定义写出流ZipOutputStream zos = null;BufferedOutputStream bos = null;try {response.setContentType("application/zip");response.setCharacterEncoding("utf-8");  //这里需要针对打出的压缩包名称的编码格式进行乱码处理:new String(("压缩包名称").getBytes("GBK"), "iso8859-1")response.setHeader("Content-Disposition", "attachment; filename=\""+ new String((zipName + ".zip").getBytes("GBK"), "iso8859-1") + "\"");OutputStream stream = response.getOutputStream();bos = new BufferedOutputStream(stream, 64 * 1024);zos = new ZipOutputStream(bos);//为后续的 DEFLATED 条目设置压缩级别zos.setLevel(1);//为要添加的文件设置文件名称zos.putNextEntry(new ZipEntry("单个的文件名称"));Writer w = new OutputStreamWriter(zos, "GBK");//这个地方可以单条数据进行写入,也可以把读取到的文件byte[]明确的转为字符串直接写入w.write("生成的csv文件内容");w.flush();} catch (Exception e) {e.printStackTrace();} finally {try {zos.close();bos.close();} catch (IOException e) {e.printStackTrace();}}}

这是最基础的操作,后续有其它需求的可在此基础上扩展,当然,如果通过HttpURLConnection获取到的getInputStream()数据流,是打好的zip包及其他格式也可以通过在此基础上扩展达到目的.

此贴为备注贴,方便以后用到的时候查看。

另附上inputStream流转为byte[]代码

/** * 将http返回的数据流转为byte[] * @param http * @return * @throws IOException */public static byte[] inputStreamToBytes(HttpURLConnection http) throws IOException {byte[] data = null;InputStream stream = http.getInputStream ();try {int len = http.getContentLength ();if (len >= 0) {data = new byte[len];int off = 0;while (off < len) {int read = stream.read (data, off, len - off);if (read < 0)throw new IOException ();off += read;}} else {ByteArrayOutputStream baos = new ByteArrayOutputStream ();byte[] buffer = new byte[4096];for (;;) {int read = stream.read (buffer, 0, buffer.length);if (read < 0)break;baos.write (buffer, 0, read);}baos.close ();data = baos.toByteArray ();}} catch (Exception e) {e.printStackTrace();} finally {stream.close ();}return data;}


0 0