InputStreamReader and BufferedReader usage and examples

  • 2020-04-01 04:32:30
  • OfStack

A, BufferedReader

. Class library:

                Java. Lang. Object 

                          Java. IO. Reader 

                                                Java. IO. BufferedReader

. Basic concepts:

                    Public class BufferedReader      Extends Reader

Efficient reading of characters, arrays, and lines by reading text from the character input stream and buffering individual characters. You can specify the size of the buffer, or you can use the default size. In most cases, the default value is large enough.

Typically, every read request made by a Reader results in a corresponding read request to the underlying character or byte stream. Therefore, it is recommended that a BufferedReader be used to wrap all readers whose read() operations might be expensive (such as FileReader and InputStreamReader).

The BufferedReader stream can read lines of text and create a BufferedReader object by passing a Reader object to the BufferedReader, because FileReader does not provide the ability to read lines of text.

The Demo:

Capture the input statement by Bufferedreader:


import java.io.*;
class BufferedReaderDemo{
 public static void main(String[] args)throws IOException { 
  BufferedReader bufferedReader =new BufferedReader(
    new InputStreamReader(System.in));
  System.out.print(" Please enter a series of text, including Spaces: "); 
  String text =bufferedReader.readLine(); 
  System.out.println(" Please enter: "+text);
 } 
}

Comments:

Throws IOException    An exception is thrown

An InputStreamReader is a bridge between the flow of bytes and the flow of characters

Second, InputStreamReader class

InputStreamReader converts a byte stream to a character stream. It is the bridge from byte flow to character flow. If no character set encoding is specified, the decoding process will use the platform's default character encoding, such as GBK.

Construction method:  

      InputStreamReader isr = new InputStreamReader(InputStream in); // constructs an InputStreamReader class for the default set of codes
      InputStreamReader isr = new InputStreamReader(InputStream in,String charsetName); // to construct a specified set of codes

InputStreamReader class.    

    Parameter in object through InputStream in = system.in; To obtain. // read the data on the keyboard.  

      Or InputStream in = new FileInputStream(String fileName); // read the data in the file. You can see that FileInputStream is a subclass of InputStream.

Main methods: int read(); // reads a single character.  

                                Int read (char [] cbuf); // stores the characters read into an array. Returns the number of characters read.

The Demo:


import java.io.*;
class InputStreamReaderDemo {
 public static void transReadNoBuf() throws IOException {
  
  //Read byte stream
  //InputStream in = System.in;//read Keyboard input. 
  InputStream in = new FileInputStream("D:\demo.txt");//Read the data from the file.
  //The translation of bytes into a stream of characters. To enable a valid conversion from bytes to characters,
  //More bytes can be read ahead of time from the underlying stream.
  InputStreamReader isr = new InputStreamReader(in);//read
  //All in one sentence.
  //InputStreamReader isr = new InputStreamReader(
  //new FileInputStream("D:\demo.txt"));
  char []cha = new char[1024];
  int len = isr.read(cha);
  System.out.println(new String(cha,0,len));
  isr.close();
 }
 public static void transReadByBuf() throws IOException {
  
  //Read byte stream
  //InputStream in = System.in;//read Data on the keyboard 
  InputStream in = new FileInputStream("D:\demo.txt");//read Data on a file. 
  //The translation of bytes into a stream of characters.
  InputStreamReader isr = new InputStreamReader(in);//read
  //Create a character stream buffer
  BufferedReader bufr = new BufferedReader(isr);//The buffer
  //BufferedReader bufr = new BufferedReader(
  //new InputStreamReader(new FileInputStream("D:\demo.txt"))); can All in one sentence.
   
  String line;
  while((line = bufr.readLine())!=null){
   System.out.println(line);
  }
  isr.close();
 }
}

Real cases of InputStreamReader and BufferedReader (non-coding set)


import java.io.*;
class UtilResource {
 private void initializeResource() {
  try {
   //Read the file and write it out as utf-8
   BufferedReader bufread;
   String read;
   bufread = new BufferedReader(new InputStreamReader(ResourceHelper
     .getResourceInputStream("pinyin.txt")));
   while ((read = bufread.readLine()) != null) {
    System.out.println(read);
   }
   bufread.close();
  } catch (FileNotFoundException ex) {
   ex.printStackTrace();
  } catch (IOException ex) {
   ex.printStackTrace();
  }
 }
}

Note: where pinying.txt is placed in the root directory of the project


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
class ResourceHelper {
 
 static BufferedInputStream getResourceInputStream(String resourceName) {
  try {
   return new BufferedInputStream(new FileInputStream(resourceName));
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }
}

Conclusion:

InputStreamReader class

It is a bridge from byte flow to character stream, in which the InputStream is enclosed. It reads one character at a time in a more advanced way, input/output in text format, and the encoding format can be specified.

BufferedReader class

BufferedReader is an extension of the Reader class that provides a general buffering method for text reading and a useful readLine that reads a line of text, reads text from a character input stream, and buffers individual characters to provide efficient reading of characters, arrays, and lines.

Ps: relationship between InputStream, InputStreamReader, and Reader

InputStream: gets the byte InputStream, after inputstream.read ("filename"), gets the byte stream

Reader: reads a stream of characters

InputStreamReader: a bridge from bytes to characters. InputStreamReader (InputStream. Read (" filename "));

Reader. Read (InputStreamReader (InputStream in)); From the byte to the character, print display.

Java.io.Reader and java.io.InputStream make up the Java input class.

Reader is used to read in 16-bit characters, that is, Unicode encoded characters; InputStream is used to read in ASCII characters and binary data.

Reader supports 16-bit Unicode character output, and InputStream supports 8-bit character output.

Reader and InputStream are two parallel and independent hierarchical organizations provided by the I/O library, 1byte = 8bits  InputStream and OutputStream are used for 8-bit streams, and Reader and Writer are used for 16-bit streams.

In the JAVA language, byte is 8-bit and char is 16-bit, so Reader and Writer are needed to process Chinese.

It is worth noting that under these two hierarchy mechanisms, there is also a bridge InputStreamReader and OutputStreamWriter that is responsible for the adaptation of InputStreamReader to Reader and OutputStream to Writer.

In Java, there are different types of Reader input streams corresponding to different data sources:

FileReader is used to enter from a file; CharArrayReader is used to input from an array of characters in a program. StringReader is used to input strings from programs; PipedReader is used to read data written to a pipe from a PipedWriter in another thread.

There are also different types of InputStream corresponding to different data sources: FileInputStream, ByteArrayInputStream, StringBufferInputStream, PipedInputStream.

In addition, there are two inputstreams that do not have a Reader type: sockets for sockets; URLConnection is used for URL connections. These two classes use getInputStream() to read the data.

Accordingly, there is a similar difference between java.io.writer and java.io.outputstream.

  As for inputstream.read (byte[] b) and inputstream.read (byte[] b,int off,int len), both methods are used to read multiple bytes from the stream, and experienced programmers will find that these two methods often do not read the number of bytes they want to read. For example, in the first method, programmers often expect the program to be able to read b. ength bytes, but in reality, the system is often unable to read that much. A closer look at the Java API specification reveals that this method is not guaranteed to read this many bytes, it is only guaranteed to read this many bytes at most (at least 1). Therefore, if you want the program to read count bytes, it is best to use the following code:


  byte[] b = new byte[count];
 int readCount = 0; //The number of bytes that have been successfully read
 while (readCount < count) {
  readCount += in.read(bytes, readCount, count - readCount);
 }

          This code is guaranteed to read count bytes, unless an IO exception is encountered or the end of the data stream (EOFException) is reached.


Related articles: