Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker DevOps


Spring Boot 将 InputStream 输入流转换为 String

Spring Boot 大约 1214 字

StreamUtils

Spring中提供了StreamUtils工具类,将InputStream转换为String

注意:不会关闭流。

使用

假设转换HttpServletRequest的输入流为String

HttpServletRequest request = xxx;
String content = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);

源码

// org.springframework.util.StreamUtils
public abstract class StreamUtils {

    /**
     * Copy the contents of the given InputStream into a String.
     * <p>Leaves the stream open when done.
     * @param in the InputStream to copy from (may be {@code null} or empty)
     * @param charset the {@link Charset} to use to decode the bytes
     * @return the String that has been copied to (possibly empty)
     * @throws IOException in case of I/O errors
     */
    public static String copyToString(@Nullable InputStream in, Charset charset) throws IOException {
        if (in == null) {
            return "";
        }

        StringBuilder out = new StringBuilder();
        InputStreamReader reader = new InputStreamReader(in, charset);
        char[] buffer = new char[BUFFER_SIZE];
        int charsRead;
        while ((charsRead = reader.read(buffer)) != -1) {
            out.append(buffer, 0, charsRead);
        }
        return out.toString();
    }

}
阅读 52 · 发布于 2023-01-24

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批