inputStream和String,Byte之间的转换

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1.import java.io.ByteArrayInputStream;

2.import java.io.ByteArrayOutputStream;

3.import java.io.IOException;

4.import java.io.InputStream;

5.

6./**

7. *

8. * @author Andy.Chen

9. * @mail Chenjunjun.ZJ@

10. *

11. */

12.public class InputStreamUtils {

13.

14. final static int BUFFER_SIZE = 4096;

15.

16. /**

17. * 将InputStream转换成String

18. * @param in InputStream

19. * @return String

20. * @throws Exception

21. *

22. */

23. public static String InputStreamTOString(InputStream in) throws Ex

ception{

24.

25. ByteArrayOutputStream outStream = new ByteArrayOutputStream();

26. byte[] data = new byte[BUFFER_SIZE];

27. int count = -1;

28. while((count = in.read(data,0,BUFFER_SIZE)) != -1)

29. outStream.write(data, 0, count);

30.

31.data = null;

32. return new String(outStream.toByteArray(),"ISO-8859-1");

33. }

34.

35. /**

36. * 将InputStream转换成某种字符编码的String

37. * @param in

38. * @param encoding

39. * @return

40. * @throws Exception

41. */

42. public static String InputStreamTOString(InputStream in,Strin

g encoding) throws Exception{

43.

44. ByteArrayOutputStream outStream = new ByteArrayOutputStream();

45. byte[] data = new byte[BUFFER_SIZE];

46. int count = -1;

47. while((count = in.read(data,0,BUFFER_SIZE)) != -1)

48. outStream.write(data, 0, count);

49.

50.data = null;

51. return new String(outStream.toByteArray(),"ISO-8859-1");

52. }

53.

54. /**

55. * 将String转换成InputStream

56. * @param in

57. * @return

58. * @throws Exception

59. */

60. public static InputStream StringTOInputStream(String in) throws Ex

ception{

61.

62. ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes

("ISO-8859-1"));

63. return is;

64. }

65.

66. /**

67. * 将InputStream转换成byte数组

68. * @param in InputStream

69. * @return byte[]

70. * @throws IOException

71. */

72. public static byte[] InputStreamTOByte(InputStream in) throws IOEx

ception{

73.

74. ByteArrayOutputStream outStream = new ByteArrayOutputStream();

75. byte[] data = new byte[BUFFER_SIZE];

76. int count = -1;

77. while((count = in.read(data,0,BUFFER_SIZE)) != -1)

78. outStream.write(data, 0, count);

79.

80.data = null;

81. return outStream.toByteArray();

82. }

83.

84. /**

85. * 将byte数组转换成InputStream

86. * @param in

87. * @return

88. * @throws Exception

89. */

90. public static InputStream byteTOInputStream(byte[] in) throws Exce

ption{

91.

92. ByteArrayInputStream is = new ByteArrayInputStream(in);

93. return is;

94. }

95.

96. /**

97. * 将byte数组转换成String

98. * @param in

99. * @return

100. * @throws Exception

101. */

102. public static String byteTOString(byte[] in) throws Exception{ 103.

104. InputStream is = byteTOInputStream(in);

105. return InputStreamTOString(is);

106. }

107.

108.}

相关文档
最新文档