Carriage return and new line with Java and readLine()

后端 未结 3 700
挽巷
挽巷 2020-12-03 05:09

I am using the following code to establish a HTTP connection and read data:

con = (HttpURLConnection) new URL(\"http://stream.twitter.com/1/statuses/sample.j         


        
相关标签:
3条回答
  • 2020-12-03 05:25

    From the javadocs:

    public String readLine() throws IOException
    

    Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
    Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
    Throws:
    IOException - If an I/O error occurs

    0 讨论(0)
  • 2020-12-03 05:33

    In Java, readLine() uses \n and \r as line feed and carriage return end characters to determine the next lines. So, when you use readLine(), then you won't get \n or \r characters to be displayed in the console as these characters will be masked by the readLine(). For more information about readLine(), refer to the official Oracle doc.

    To avoid such behavior, we should use read() method from BufferedReader package. The following sample snippet will help to understand how these \n and \r are getting recognized using read().

    Let's say you have a file called test_lineFeed.txt which contains line breaks, and if you want to replace them with some defined format like "CR-LF" (CR --> Carriage return, LF --> Line Feed), then use the following snippet.

    BufferedReader reader1 = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream("/home/test_lineFeed.txt")
                ));
    
        int s1 = 0;
        String formattedString = "";
        while ((s1 = reader1.read()) != -1) {
    
            char character = (char) s1;
    
            System.out.println("Each Character: "+character+" its hexacode(Ascii): "+Integer.toHexString(character));
            //output : "0a" --> \n 
            //output : "0d" --> \r
    
            if (character == '\n'){
                formattedString+=" <LF> ";
            }else if (character =='\r'){
                formattedString+=" <CR> ";
            }else
                formattedString+=character;
    
        }
        System.out.println(formattedString);
    
    0 讨论(0)
  • 2020-12-03 05:41

    If rd is of type BufferedReader there is no way to figure out if readLine() returned something that ended with \n, \r or \r\n... the end-of-line characters are discarded and not part of the returned string.

    If you really care about these characters, you can't go through readLine(). You'll have to for instance read the characters one by one through read().

    0 讨论(0)
提交回复
热议问题