一. String 转换为InputStream
String str = "String 与 inputStream转换";
InputStream ins1 = new ByteArrayInputStream(str.getBytes());
InputStream ins2 = new ByteArrayInputStream(str.getBytes("UTF-8"));
二. InputStream 转为 String
方法一:利用bufferedReader
1: public String convertToString(InputStream is){
2: BufferedReader bReader = new BufferedReader(new InputStreamReader(is));
3: StringBuffer buffer = new StringBuffer();
4: String line = null;
5: try {
6: while((line = bReader.readLine())!=null){
7: buffer.append(line);
8: }
9: } catch (IOException e) {
10: // TODO Auto-generated catch block
11: e.printStackTrace();
12: }finally{
13: try {
14: bReader.close();
15: } catch (IOException e) {
16: // TODO Auto-generated catch block
17: e.printStackTrace();
18: }
19: }
20: return buffer.toString();
21: }
方法二:
1: public String convertToString(InputStream is){
2: StringBuffer buffer = new StringBuffer();
3: byte[] b = new byte[1024];
4: try {
5: for(int n; (n = is.read(b))!=-1;)
6: buffer.append(new String(b,0,n));
7: return buffer.toString();
8: } catch (IOException e) {
9: // TODO Auto-generated catch block
10: e.printStackTrace();
11: }finally{
12: try {
13: is.close();
14: } catch (IOException e) {
15: // TODO Auto-generated catch block
16: e.printStackTrace();
17: }
18: }
19: }
方法三:
1: public String convertToString(InputStream is){
2: ByteArrayOutputStream os = new ByteArrayOutputStream();
3: int i = -1;
4: try {
5: while((i = is.read())!=-1){
6: os.write(i);
7: }
8: return os.toString();
9: } catch (IOException e) {
10: // TODO Auto-generated catch block
11: e.printStackTrace();
12: return null;
13: }finally{
14: try {
15: os.close();
16: } catch (IOException e) {
17: // TODO Auto-generated catch block
18: e.printStackTrace();
19: }
20: }
21: }
时间: 2024-10-12 14:02:33