1. String --> InputStream
InputStream String2InputStream (String str ){
ByteArrayInputStream stream = new ByteArrayInputStream (str. getBytes ());
Return stream;
}
2. InputStream --> String
String inputStream2String (InputStream is ){
BufferedReader in = new BufferedReader (new InputStreamReader (is ));
StringBuffer buffer = new StringBuffer ();
String line = "";
While (line = in. readLine ())! = Null ){
Buffer. append (line );
}
Return buffer. toString ();
}
I saw another method on the internet today.
String all_content = null;
Try {
All_content = new String ();
InputStream ins = the obtained input stream;
ByteArrayOutputStream outputstream = new ByteArrayOutputStream ();
Byte [] str_ B = new byte [2, 1024];
Int I =-1;
While (I = ins. read (str_ B)> 0 ){
Outputstream. write (str_ B, 0, I );
}
All_content = outputstream. toString ();
} Catch (Exception e ){
E. printStackTrace ();
}
The above two methods are faster, but memory consumption is relatively high. The latter is slow and consumes less resources.
3. File --> InputStream
InputStream in = new InputStream (new FileInputStream (File ));
4. InputStream --> File
Public void inputstreamtofile (InputStream ins, File file ){
OutputStream OS = new FileOutputStream (file );
Int bytesRead = 0;
Byte [] buffer = new byte [8192];
While (bytesRead = ins. read (buffer, 0, 8192 ))! =-1 ){
OS. write (buffer, 0, bytesRead );
}
OS. close ();
Ins. close ();
}