Java network programming stream--readline()

        I encountered such a problem in the production environment two days ago. The system failed to run the batch task at the end of the day. I found that it stopped on the task of reading the ftp service file remotely. It is caused by the teammates using BufferedReader.readline() in the remote network connection. Therefore, let the team members adjust the business to download files from ftp first, and then read the files locally to avoid using BufferedReader.readline() in the network connection.

       The BufferedReader.readline() method has an implicit bug where it doesn't necessarily interpret a carriage return as the end of a line. In contrast, readline() only recognizes newlines or carriage return/linefeed pairs. When a carriage return is detected in the stream, readline() waits to see if the next character is a newline before continuing. If it is a newline, discard the carriage return and newline, and return the line as a String. If it's not a newline, just throw away the carriage return and return the line as a String, and the extra character will be read as part of the next line. However, if the carriage return is the last character of the stream (which is likely to happen if the stream was generated from Macintosh or Macintosh-created text), then readline() hangs, waiting for the last character to appear, But this character never appears.

This problem is less obvious when reading a file, because there must be a next character: if there are no more characters, the end of the stream will be indicated by -1. However, in persistent network connections (like connections used for FTP and HTTP with the latest model), the server or client may simply stop sending data after the last character and wait for a response without actually closing the connection. If you're lucky, the connection will eventually time out on one end or the other and you'll get an IOException, which might take at least a minute or two, but that's fine. If you are not lucky, the program will hang forever.

public class ReadLine {

    public static void main(String[] args) {  
        // System.in is standard input (gets the value entered by the keyboard),  
        // InputStreamReader converts byte stream to character stream and byte stream to BufferedReader  
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
        String line;  
        try {  
            // readLine() is a blocking method. When the keyboard is entered, click Enter, and the obtained value will not be null, and it will always be in a blocking state.  
            while ((line = br.readLine()) != null) {  
                System.out.println("dd" + line);  
            }  
        } catch (IOException e) {  
            e.printStackTrace ();  
        }  
  
    }  
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326441053&siteId=291194637