1.String to InputStream
String str = "string and InputStream are converted to each other";
InputStream in = new Bytearrayinputstream (Str.getbytes ());
InputStream in = new Bytearrayinputstream (str.getbytes ("UTF-8"));
It is recommended that this method be used to specify that code is not easy to garbled.
2.InputStream to String
Here are a few ways to do this.
Method 1:
Public String convertstreamtostring (InputStream is) {
BufferedReader reader = new BufferedReader (new InputStreamReader (IS));
StringBuilder sb = new StringBuilder ();
String line = null;
try {
while (line = Reader.readline ())!= null) {
Sb.append (line + "n");
}
catch (IOException e) {
E.printstacktrace ();
finally {
try {
Is.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
return sb.tostring ();
}
Method 2:
public string inputstream2string (inputstream in) throws ioexception {
StringBuffer out = new stringbuffer ();
byte[] b = new byte[4096];
for (int n; (n = in.read (b)) != -1;) {
out.append (new String (b, 0, N));
}
return out.tostring ();
}
Method 3:
public static string inputstream2string (inputstream is) throws ioexception{
bytearrayoutputstream baos = new ByteArrayOutputStream ();
int i=-1;
while ((I=is.read ())!=-1) {
baos.write (i);
}
return baos.tostring ();
}