一、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主要用於將數據寫入到指定的流中,常見的有文件流和網路流。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/241216.html
微信掃一掃
支付寶掃一掃