java中的stream之字符串与stream之间的相互转换

string转化为stream(使用InputStream)

public static InputStream strToStream(String str) {
        if (StringUtils.isNotBlank(str)) {
            return new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
        }
        return null;
    }

string转化为stream(使用InputStreamReader)

public static InputStreamReader strToStreamReader(String str) {
        if (StringUtils.isNotBlank(str)) {
            return new InputStreamReader(new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)));
        }
        return null;
    }

stream转化为string(使用InputStream)

public static String streamToStr(InputStream inputStream) {
        if (inputStream != null) {
            try (BufferedInputStream reader = new BufferedInputStream(inputStream)) {
                return IOUtils.toString(reader, StandardCharsets.UTF_8);
            } catch (IOException e) {
                log.error("Failed to change stream to string", e);
            }
        }
        return null;
    }

stream转化为string(使用InputStreamReader)

public static String streamReaderToStr(InputStreamReader inputStreamReader) {
        if (inputStreamReader != null) {
            try {
                return IOUtils.toString(inputStreamReader);
            } catch (IOException e) {
                log.error("Failed to change streamReader to string", e);

            }
        }
        return null;
    }

测试

@Test
    public void test_change_str_and_stream() {
        InputStream inputStream = StreamUtil.strToStream("你好");
        System.out.println("inputStream is "+inputStream);
        String str = StreamUtil.streamToStr(inputStream);
        System.out.println(str);
        InputStreamReader inputStreamReader = StreamUtil.strToStreamReader("你好");
        System.out.println("inputStreamReader is "+inputStreamReader);
        String strReader = StreamUtil.streamReaderToStr(inputStreamReader);
        System.out.println(strReader);
    }
    
    //inputStream is java.io.ByteArrayInputStream@6c629d6e
	//你好
	//inputStreamReader is java.io.InputStreamReader@5a42bbf4
	//你好

你可能感兴趣的:(Java,java)