1. Why do character streams and byte streams need to be converted?
This is because there are times when the system gives you only a byte stream, such as system.in standard input stream. is the byte stream. You want to get the input from the user on the keyboard, only by converting it to reader with the conversion stream, to make it easier for your program to read the input. Another example is that the socket in the getInputStream () is clearly only to provide you with a byte stream, you can not directly use, you have to give him a inputstreamreader () to read. The character that the network transmits.
2. How does the byte stream and character stream convert?
2.1. Byte stream converted to character stream: InputStreamReader
2.2. Character stream conversion to byte stream: Inputstreamwriter
3. Specific applications
3.1-byte stream converted to character stream
PackageSe.io;ImportJava.io.*; Public classInputstreamreadertest { Public Static voidMain (string[] args) {Try { //Building a byte input stream objectFileInputStream FileInputStream =NewFileInputStream ("E:\\test\\data3.txt"); //Building a byte character conversion stream objectInputStreamReader InputStreamReader =NewInputStreamReader (FileInputStream); //building character input stream objectsBufferedReader BufferedReader =NewBufferedReader (InputStreamReader); //reading Data Char[] chars =New Char[1024]; intOff = 0; while(Bufferedreader.ready ()) {off=Bufferedreader.read (chars); } //Print OutputString s =NewString (chars,0, off); System.out.println (s); //Close the streamBufferedreader.close (); Inputstreamreader.close (); Fileinputstream.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } }}
3.2 character stream converted to byte stream
PackageSe.io;ImportJava.io.*; Public classOutputstreamwritertest { Public Static voidMain (string[] args) {Try { //building an output stream byte objectFileOutputStream FileOutputStream =NewFileOutputStream ("E:\\test\\data4.txt"); //building an output stream Byte character conversion objectOutputStreamWriter OutputStreamWriter =NewOutputStreamWriter (FileOutputStream); //building character output stream objectsBufferedWriter BufferedWriter =NewBufferedWriter (OutputStreamWriter); //Building Data Char[] chars =New Char[3]; chars[0] = ' a '; chars[1] = ' B '; chars[2] = ' Medium '; //Output DataBufferedwriter.write (chars); //Close the streamBufferedwriter.close (); Outputstreamwriter.close (); Fileoutputstream.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } }}
Java core programming--io stream of characters and Byte stream conversion (four)