InputStreamReader and BufferedReader usages and examples explained _java

Source: Internet
Author: User

First, BufferedReader class

. Owning class Library:

Java.lang.Object

Java.io.Reader

Java.io.BufferedReader

. Basic concepts:

public class BufferedReader extends Reader

Reads text from a character input stream and buffers individual characters to enable efficient reading of characters, arrays, and rows. 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, each read request made by reader causes the corresponding read request to be made to the underlying character or byte stream. Therefore, it is recommended to use BufferedReader to wrap all Reader (such as FileReader and InputStreamReader) whose read () operation may be expensive.

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

. Demo:

Capture the entered 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, can include spaces:"); 
  String text =bufferedreader.readline (); 
  System.out.println ("Please enter text:" +text);
 } 

Annotations:

Throws IOException throws an exception

InputStreamReader is a bridge of byte flow to character streams

Second, InputStreamReader class

InputStreamReader converts a stream of bytes into a string of characters. is a bridge of byte flow to character streams. If you do not specify a character set encoding, the decoding process uses the platform default character encoding, such as: GBK.

Construction Method:

InputStreamReader ISR = new InputStreamReader (InputStream in);//InputStreamReader class that constructs a default encoding set
InputStreamReader ISR = new InputStreamReader (InputStream in,string charsetname);//construct a specified encoding set

InputStreamReader class.

The parameter in object is obtained by inputstream in = system.in; 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 inputstream subclass.

Main method: int read ();//Read single character.

int read (char []cbuf);//Fu Cun The read to the array. Returns the number of characters read.

. Demo:

Import java.io.*;
   Class Inputstreamreaderdemo {public static void Transreadnobuf () throws IOException {/** * does not have a buffer and can only use the Read () method.
  *///Read byte stream//inputstream in = system.in;//read input from keyboard.
  InputStream in = new FileInputStream ("D:\\demo.txt");//Read the file's data. The conversion of a byte to a character stream.
  To enable a valid conversion from byte to character,//You can read more bytes from the underlying stream in advance.
  InputStreamReader ISR = new InputStreamReader (in);//read///A synthesis to a 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 ();
   The public static void Transreadbybuf () throws IOException {/** * uses a buffer to use the read () and ReadLine () methods of the Buffer object. 
  ///Read byte stream//inputstream in = system.in;//Read the data on the keyboard inputstream in = new FileInputStream ("D:\\demo.txt");//Read the data on the file.
  The conversion of a byte to a character stream.
  InputStreamReader ISR = new InputStreamReader (in);//read//Create character stream buffer BufferedReader bufr = new BufferedReader (ISR);//buffering BufferedReader BUFR = new BufferedReader (New FileInputStream ("D:\\demo.txt")) (//new inputstreamreader) can be synthesized into one sentence.
  /*int ch = 0;
  ch = bufr.read ();
  System.out.println ((char) ch);
  */String line;
  while (line = Bufr.readline ())!=null) {System.out.println (line);
 } isr.close ();

 }
}

Three, InputStreamReader, BufferedReader Real case (non-coding set)

Import java.io.*;
Class Utilresource {
 private void Initializeresource () {
  try {
   //Read the file, and write it in utf-8 form
   BufferedReader Bufread;
   String Read;
   Bufread = new BufferedReader (Resourcehelper
     . Getresourceinputstream ("Pinyin.txt")) (new InputStreamReader);
   while (read = Bufread.readline ())!= null) {
    System.out.println (read);
   }
   Bufread.close ();
  } catch (FileNotFoundException ex) {
   ex.printstacktrace ();
  } catch (IOException ex) {
   ex.printstacktrace ();
  }
 }
}

Note: Where Pinyin.txt is placed in the root directory of the project

Import Java.io.BufferedInputStream;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Class Resourcehelper {
 /**
  * @param resourcename *
  @return * 
  @return/
 static Bufferedinputstream Getresourceinputstream (String resourcename) {
  try {return
   new Bufferedinputstream (new FileInputStream (resourcename));
  catch (FileNotFoundException e) {
   //TODO auto-generated catch block
   e.printstacktrace ();
  }
  return null;
 }
}

Summarize:

InputStreamReader class

It is the bridge of byte flow to character stream, the InputStream is sealed in the inside, it reads one character at a time in a higher level, the input/output in text format, can specify the encoding format;

BufferedReader class

BufferedReader is extended by the reader class to provide a universal buffer for text reading, and provides a very useful readline, reads a line of text, reads text from a character input stream, buffers individual characters, and provides efficient reading of characters, arrays, and rows.

The relationship between Ps:inputstream, InputStreamReader and Reader

InputStream: Get byte input stream, Inputstream.read ("filename"), get word throttling

Reader: The character stream is read

InputStreamReader: A bridge from Byte to character. InputStreamReader (Inputstream.read ("filename"));

Reader.read (InputStreamReader (InputStream in)) can be changed from byte to character and printed.

Java.io.Reader and Java.io.InputStream form the Java input class.

Reader is used to read 16-bit characters, which are Unicode-encoded characters, while InputStream is used to read ASCII characters and binary data.

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

Reader and InputStream are two sets of parallel independent hierarchies provided by the I/o library, 1byte = 8bits InputStream, OutputStream is used to handle 8-bit flow, reader, writer is used to handle 16-bit streams.

In the Java language, the byte type is 8-bit and the char type is 16-bit, so you need to use reader and writer when dealing with Chinese.

It is worth noting that, under these two hierarchies, there is also a bridge inputstreamreader, OutputStreamWriter is responsible for InputStream to reader adaptation and from OutputStream to writer adaptation.

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

FileReader is used to enter from a file; CharArrayReader is used to enter from a character array in a program; StringReader to input from a string in a program; Pipedreader to read pipedwriter from another thread The data to be written to the pipe.

There are also different types of inputstream input streams corresponding to different data sources: Fileinputstream,bytearrayinputstream,stringbufferinputstream, PipedInputStream.

In addition, there are two inputstream input streams that do not have a corresponding Reader type: The socket is used for the socket; URLConnection is used for the URL connection. These two classes use getInputStream () to read data.

Correspondingly, Java.io.Writer and Java.io.OutputStream also have similar differences.

With regard to 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 are often Cannot read bytes of the number that they want to read. For example, the first method, programmers often want the program to read B.length bytes, and the reality is that the system is often not read so much. A careful reading of Java's API instructions shows that this method does not guarantee that you can read so many bytes, it can only guarantee a maximum of 1 bytes. Therefore, if you want the program to read count bytes, it's better 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);
 }

Use this code to ensure that count bytes are read unless midway through an IO exception or at the end of the data stream (eofexception)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.