Experience with the read () and ReadLine () methods of BufferedReader in Java

Source: Internet
Author: User

BufferedReader's ReadLine () method is blocking, and returns null if the end of the stream is reached, but if the client's socket is closed and destroyed, an IO exception is generated. The normal approach is to use Socket.close () to close the unwanted socket.

From a file with a number of rows, sequentially read each row, after processing the output, if the following method, you will appear in addition to the first line of the layman first character loss phenomenon

String str = NULL;
Br=new BufferedReader (New FileReader (FileName));
do{
str = Buf.readline ());
}while (Br.read ()!=-1);
The following usage will make each line less than the first character
while (Br.read ()! =-1) {
str = Br.readline ();
}
The reason is that br.read ()! =-1 This judging condition. Because in the execution of this condition, it has actually read a character, but here does not have to read the character to do processing, so there will be less one character, if you write here is while (Br.readline ()! =null) There will be fewer rows in a row!

It is recommended that the following methods
String str = NULL;
while ((str = br.readline ()) = null) {
System.out.println (str);//At this point, Str saves a line of string
}

This should make it possible to get one line without losing characters.

Although the writing IO aspect of the program is not much, but Bufferedreader/bufferedinputstream has been used several times, the reason is:

    • It has a very special method: ReadLine (), especially convenient to use, each read back is a row, save a lot of manual splicing buffer trivial;
    • It is more efficient than a character/byte read, convert, return, it has a buffer, read full buffer to return; In general, it is recommended to use them to wrap other reader/inputstream, making reading data more efficient.
    • For a file, you often encounter one line, which is particularly consistent with the scenario.

This time in the development of Bluetooth, using two Bluetooth to each other data (that is, a hair a receive), Bluecove this open source component has been the data read all encapsulated into InputStream, it is equivalent to the usual IO read, it is natural to use the ReadLine () came.

Send data:

[Java]View Plaincopy
    1. BufferedWriter output = new BufferedWriter (new OutputStreamWriter (Conn.openoutputstream ()));
    2. int i = 1;
    3. String message = "message" + I;
    4. while (isrunning) {
    5. Output.write (message+"/n");
    6. i++;
    7. }

Read data:

[Java]View Plaincopy
    1. BufferedReader input = new BufferedReader (new InputStreamReader (M_conn.openinputstream ()));
    2. String message = "";
    3. String line = null;
    4. while (line = M_input.readline ()) = null) {
    5. Message + = line;
    6. }
    7. SYSTEM.OUT.PRINTLN (message);

The above is an excerpt of the code that uses this code to discover that writing data succeeds every time, while the read data side has no data output (unless the stream is switched off). After the toss, the original there are several big problems to understand:

    • Mistakenly assume that readline () returns NULL if no data is read (because the other Read method returns 1 when no data is read), while in fact ReadLine () is a blocking function that is always blocked when no data is read, instead of returning null Because ReadLine () is blocked, the phrase System.out.println (message) is not executed at all, so there is no output at the receiving end. To execute to SYSTEM.OUT.PRINTLN (message), one method is to turn off the stream after sending the data, so that ReadLine () ends the blocking state and can get the correct result, but it is obvious that the data stream cannot be closed one line at a time Another way is to put SYSTEM.OUT.PRINTLN (message) in the while loop body.
    • ReadLine () returns a null value only if the data flow has an exception or if the other end is close ().
    • If you do not specify a buffer size, the buffer used by ReadLine () has 8,192 characters. Only "/R", "/n", "/r/n" will be returned until the buffer size is reached.

The essence of ReadLine () (Below is extracted from the JDK source code):

[Java]View Plaincopy
  1. String ReadLine (boolean ignorelf) throws IOException {
  2. StringBuffer s = null;
  3. int Startchar;
  4. synchronized (lock) {
  5. Ensureopen ();
  6. boolean OMITLF = Ignorelf | | SKIPLF;
  7. Bufferloop:
  8. for (;;) {  
  9. if (Nextchar >= nchars)
  10. Fill (); //Read the data here
  11. if (Nextchar >= nchars) {/ * EOF * /
  12. if (s! = null && s.length () > 0)
  13. return s.tostring ();
  14. Else
  15. return null;
  16. }
  17. ...... //Other
  18. }
  19. Private void Fill () throws IOException {
  20. ..../Other
  21. int n;
  22. Do {
  23. n = in.read (CB, DST, CB.LENGTH-DST); //Substance
  24. } while (n = = 0);
  25. if (n > 0) {
  26. Nchars = DST + N;
  27. Nextchar = DST;
  28. }
  29. }

As seen from the above, ReadLine () is called Read (char[] cbuf, int off, int len) to fetch the data, followed by "/R" or "/n" for data processing.

The Java I/O book also says:

Public String ReadLine () throws IOException
This method returns a string, contains a line of text from a text file. /r,/N, and/r/n is assumed to is line breaks and is not included in the returned string. This method was often used when reading user input from system.in, since most platforms only send the user's input to the R Unning program after the user have typed a full line (that's, hit the Return key).
ReadLine () have the same problem with line ends that DataInputStream ' s ReadLine () method have; That's, the potential to hang on a lone carriage return this ends the stream . This problem was especially acute on networked connections, where ReadLine () should never was used.

Summary, use ReadLine () Be sure to note:

    1. Read-in data should be noted with the/R or/N or/r/n
    2. Blocks when there is no data and returns null if the data stream is abnormal or fractured
    3. When using a data stream such as a socket, avoid using readline () so that it is not blocked to wait for a line break/carriage return

The previous study time also did not care too much, in the project use to only then found hehe

1. read a TXT file in many ways I use a character stream to read (for convenience)

FileReader FR = new FileReader ("F:\\testjava.java");
BufferedReader bf = new BufferedReader (FR);

Here to read

int b;
while ((B=bf.read ())!=-1) {
System.out.println (Bf.readline ());
}

found that the first character of each line is not displayed, the reason: B=bf.read ())!=-1 each time will read a byte first, so the back of the Bf.readline ());
Reading is one byte less per line

Therefore, you should use

String valuestring = null;
while ((Valuestring=bf.readline ())!=null) {


System.out.println (valuestring);
}

Experience with the read () and ReadLine () methods of BufferedReader in Java

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.