一、InputStream转Map
我们在处理请求体时,会将请求体读取成InputStream流,这时我们经常需要将流转成Map,这里就以HttpServletRequest的过滤器为例。
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; // 将inputStream转成Map Map<String, String> paramMap = getParameterMap(request.getInputStream(), request.getContentType()); // do something chain.doFilter(req, res); } /** * 将InputStream转成Map * * @param inputStream * 请求流 * @param contentType * Content-Type * @return Map 对象 * @throws UnsupportedEncodingException * @throws IOException */ @SuppressWarnings("rawtypes") private Map<String, String> getParameterMap(InputStream inputStream, String contentType) throws UnsupportedEncodingException, IOException { Map<String, String> paramMap = new HashMap<String, String>(); if (contentType != null && contentType.contains("multipart/form-data")) { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); try { List fileItems = servletFileUpload.parseRequest(new ServletRequestContext(request)); Iterator it = fileItems.iterator(); while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { paramMap.put(fileItem.getFieldName(), fileItem.getString()); } } } catch (FileUploadException e) { LOG.error("Get parameter map failed! ", e); } } else { byte[] body = IOUtils.readFully(inputStream, -1, false); paramMap = JsonParserUtils.toMap(new String(body, "UTF-8")); } return paramMap; }
二、OutputStream转文件
将OutputStream转成文件在日常开发中是十分常见的需求,这里给出一个方法实现。
/** * 将OutputStream流写入文件 * * @param outputStream * 源流 * @param filePath * 目标文件路径 * @throws IOException */ public static void outputStreamToFile(OutputStream outputStream, String filePath) throws IOException { byte[] buffer = new byte[1024]; int len; FileOutputStream fos = null; try { fos = new FileOutputStream(filePath); while ((len = outputStream.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.flush(); } finally { if (fos != null) { fos.close(); } } }
三、OutputStream编码
在将OutputStream转成String时,要注意编码格式,否则可能会出现乱码的情况。
OutputStream outputStream = new ByteArrayOutputStream(); try { outputStream.write("你好".getBytes("UTF-8")); } catch (IOException e) { e.printStackTrace(); } String result = outputStream.toString("UTF-8"); System.out.println(result);
四、OutputStream用法
OutputStream一般是作为写入数据的流,默认将数据写入到流中,然后再从流中读取到另一段进行处理。
// 文件流 OutputStream outputStream = new FileOutputStream(new File("output.txt")); // 网络流 OutputStream outputStream = socket.getOutputStream();
五、OutputStream用于
OutputStream主要用于将数据写入到指定的流中,常见的有文件流和网络流。