InputStream流转换成String字符串

红太狼 2022-12-21 03:22 259阅读 0赞
  1. public class StreamUtils {
  2. private static int _buffer_size = 1024;
  3. /** * InputStream流转换成String字符串 * @param inStream InputStream流 * @param encoding 编码格式 * @return String字符串 */
  4. public static String inputStream2String(InputStream inStream, String encoding){
  5. String result = null;
  6. ByteArrayOutputStream outStream = null;
  7. try {
  8. if(inStream != null){
  9. outStream = new ByteArrayOutputStream();
  10. byte[] tempBytes = new byte[_buffer_size];
  11. int count = -1;
  12. while((count = inStream.read(tempBytes, 0, _buffer_size)) != -1){
  13. outStream.write(tempBytes, 0, count);
  14. }
  15. tempBytes = null;
  16. outStream.flush();
  17. result = new String(outStream.toByteArray(), encoding);
  18. outStream.close();
  19. }
  20. } catch (Exception e) {
  21. result = null;
  22. } finally {
  23. try {
  24. if(inStream != null) {
  25. inStream.close();
  26. inStream = null;
  27. }
  28. if(outStream != null) {
  29. outStream.close();
  30. outStream = null;
  31. }
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. return result;
  37. }
  38. }

发表评论

表情:
评论列表 (有 0 条评论,259人围观)

还没有评论,来说两句吧...

相关阅读