java InputStream转string

常用的几种InputStream 和String 互相转换的方法。

1.

            InputStream inputStream = resource.getInputStream();
			byte[] bytes = new byte[0];
			bytes = new byte[inputStream.available()];
			inputStream.read(bytes);
            System.out.println("输出"+bytes );

2.(个人建议这种)

			InputStream inputStream = resource.getInputStream();
			
			StringBuilder sb = new StringBuilder();
			String line;

			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
			while ((line = br.readLine()) != null) {
			    sb.append(line);
			}
			
			String str = sb.toString();
			System.out.println("输出"+str );

3. Apache (方便)

String str = IOUtils.toString(inputStream, "utf-8");

 

将String转换为InputStream

1.

InputStream is = new ByteArrayInputStream(str.getBytes());

2.Apache

InputStream targetStream = IOUtils.toInputStream(str, StandardCharsets.UTF_8.name());

 

你可能感兴趣的:(java)