[Java iO] _ memory operation stream notes
Objectives of this Chapter
Master the usage of Memory Operation streams
Bytearrayinputstream and bytearrayoutputstream
In the program described earlier, both output and input come from the file. Of course, you can also set the output location on the memory. In this case, bytearrayinputstream and bytearrayoutputstream are used to complete the input and output functions.
Bytearrayinputstream mainly writes content to the memory, while
Bytearrayoutputstream mainly outputs data in the memory.
Format:
Public class bytearrayinputstream extends inputstream
Public class bytearrayoutputstream extends outputstream
Constructor:
Public bytearrayinputstream (byte [] BUF)
The following code uses the memory operation stream to convert uppercase and lowercase letters.
Import Java. io. *; public class bytearraydemo01 {public static void main (string [] ARGs) {string STR = "helloworld"; bytearrayinputstream Bis = NULL; bytearrayoutputstream Bos = NULL; bis = new bytearrayinputstream (Str. getbytes (); Bos = new bytearrayoutputstream (); int temp = 0; while (temp = bis. read ())! =-1) {char c = (char) temp; Bos. write (character. tolowercase (c); // reduce the number of characters} // all the data is in bytearrayoutputstream string newstr = Bos. tostring (); // retrieve the content try {bis. close ();} catch (ioexception e) {e. printstacktrace ();} system. out. println (newstr );}}
If you want to change a character to lowercase, you can use the packaging class: character
In fact, you can also instantiate outputstream or inputstream by transforming up.
Import Java. io. *; public class bytearraydemo02 {public static void main (string [] ARGs) throws exception {string STR = "helloworld"; inputstream Bis = NULL; outputstream Bos = NULL; bis = new bytearrayinputstream (Str. getbytes (); Bos = new bytearrayoutputstream (); int temp = 0; while (temp = bis. read ())! =-1) {char c = (char) temp; Bos. write (character. tolowercase (c); // reduce the number of characters} // all the data is in bytearrayoutputstream string newstr = Bos. tostring (); // retrieve the content try {bis. close ();} catch (ioexception e) {e. printstacktrace ();} system. out. println (newstr );}}
In fact, the above operations can reflect the object polymorphism. By instantiating different sub-classes of objects, the functions are also different, which is equivalent to different output. If it is a file, filexxx is used, if the memory is used, bytearrayxxx is used.