ServletOutputStream 如何转 InputStream
时间: 2023-10-25 20:08:12 浏览: 248
handleStream ServletOutputStream out = response.getOutputStream(); InputStream i
如果您想将 `ServletOutputStream` 转换为 `InputStream`,可以使用 `PipedInputStream` 和 `PipedOutputStream` 来实现。
1. 创建 `PipedInputStream` 和 `PipedOutputStream` 对象:
```java
PipedOutputStream pipedOutputStream = new PipedOutputStream();
PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
```
2. 在 `ServletOutputStream` 中写入数据,并将数据通过 `PipedOutputStream` 写入 `PipedInputStream`:
```java
ServletOutputStream servletOutputStream = response.getOutputStream();
byte[] data = "Hello World".getBytes();
servletOutputStream.write(data);
servletOutputStream.flush();
servletOutputStream.close();
pipedOutputStream.write(data);
pipedOutputStream.flush();
pipedOutputStream.close();
```
3. 最后,您可以从 `PipedInputStream` 中读取数据:
```java
int length = 0;
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((length = pipedInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, length);
}
byte[] result = byteArrayOutputStream.toByteArray();
System.out.println(new String(result));
```
完整代码示例:
```java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
ServletOutputStream servletOutputStream = response.getOutputStream();
byte[] data = "Hello World".getBytes();
servletOutputStream.write(data);
servletOutputStream.flush();
servletOutputStream.close();
PipedOutputStream pipedOutputStream = new PipedOutputStream();
PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
pipedOutputStream.write(data);
pipedOutputStream.flush();
pipedOutputStream.close();
int length = 0;
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((length = pipedInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, length);
}
byte[] result = byteArrayOutputStream.toByteArray();
System.out.println(new String(result));
}
```
阅读全文