String与IO流的转换

一、String与InputStream

1、String --> InputStream

//字符串转inputStream
InputStream is =new ByteArrayInputStream(ins.getBytes());
//InputStream转字符串
byte[] b = new byte[ins.getBytes().length];
is.read(b);
System.out.println(new String(b));
System.out.println("ok");
is.close();
String string;
InputStream is = new ByteArrayInputStream(string.getBytes());

2、InputStream --> String

ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
while ((i = is.read()) != -1) {
baos.write(i);
}
String str = baos.toString();
System.out.println(str);

 

二、String与OutputStream

1、String --> OutputStream


OutputStream os = System.out;
os.write(string.getBytes());

2、OutputStream --> String


ByteArrayOutputStream baos = new ByteArrayOutputStream();//向OutPutStream中写入,如 message.writeTo(baos);
String str = baos.toString();

posted @ 2018-08-08 09:31  IT螺丝刀  阅读(371)  评论(0)    收藏  举报