天天看點

回車(CR)與換行(LF)

一、“回車”(Carriage Return)和“換行”(Line Feed)的來曆

      在計算機還沒有出現之前,有一種叫做電傳打字機(Teletype Model 33,Linux/Unix下的tty概念也來自于此)的玩意,每秒鐘可以打10個字元。但是它有一個問題,就是打完一行換行的時候,要用去0.2秒,正好可以打兩個字元。要是在這0.2秒裡面,又有新的字元傳過來,那麼這個字元将丢失。

      于是,研制人員想了個辦法解決這個問題,就是在每行後面加兩個表示結束的字元。一個叫做“回車”,告訴打字機把列印頭定位在左邊界;另一個叫做“換行”,告訴打字機把紙向下移一行。這就是“換行”和“回車”的來曆。

二、計算機裡的“回車”與“換行”

請看下面這段程式:

public class CRLFTest {

    public static void main(String[] args) {
        // 1. 中間包含\n
        String str = new String("Hello, World! \nThis is new line.");
        byte[] bytes = str.getBytes();

        System.out.println(str);
        for (int i = 0; i < bytes.length; i++) {
            System.out.print(bytes[i] + " ");
        }
        System.out.println();

        // 2. 中間包含\n\r
        str = new String("Hello, World! \n\rThis is new line.");
        bytes = str.getBytes();

        System.out.println(str);
        for (int i = 0; i < bytes.length; i++) {
            System.out.print(bytes[i] + " ");
        }
        System.out.println();

        // 3. 中間包含\r
        str = new String("Hello, World! \rThis is new line.");
        bytes = str.getBytes();

        System.out.println(str);
        for (int i = 0; i < bytes.length; i++) {
            System.out.print(bytes[i] + " ");
        }
        System.out.println(new Date());
    }
}
           

 以下是該程式在Windows, Linux, Mac三種環境下的運作結果: 1、Windows下的運作結果:

Hello, World! 
This is new line.
72 101 108 108 111 44 32 87 111 114 108 100 33 32 10 84 104 105 115 32 105 115 32 110 101 119 32 108 105 110 101 46 
Hello, World! 

This is new line.
72 101 108 108 111 44 32 87 111 114 108 100 33 32 10 13 84 104 105 115 32 105 115 32 110 101 119 32 108 105 110 101 46 
Hello, World! 
This is new line.
72 101 108 108 111 44 32 87 111 114 108 100 33 32 13 84 104 105 115 32 105 115 32 110 101 119 32 108 105 110 101 46 Wed May 25 11:28:42 CST 2011
           

 2、Linux下的運作結果:

Hello, World! 
This is new line.
72 101 108 108 111 44 32 87 111 114 108 100 33 32 10 84 104 105 115 32 105 115 32 110 101 119 32 108 105 110 101 46 
Hello, World! 
This is new line.
72 101 108 108 111 44 32 87 111 114 108 100 33 32 10 13 84 104 105 115 32 105 115 32 110 101 119 32 108 105 110 101 46 
This is new line.
72 101 108 108 111 44 32 87 111 114 108 100 33 32 13 84 104 105 115 32 105 115 32 110 101 119 32 108 105 110 101 46 
           

 3、Mac下的運作結果:

Hello, World! 
This is new line.
72 101 108 108 111 44 32 87 111 114 108 100 33 32 10 84 104 105 115 32 105 115 32 110 101 119 32 108 105 110 101 46 
Hello, World! 

This is new line.
72 101 108 108 111 44 32 87 111 114 108 100 33 32 10 13 84 104 105 115 32 105 115 32 110 101 119 32 108 105 110 101 46 
Hello, World! 
This is new line.
72 101 108 108 111 44 32 87 111 114 108 100 33 32 13 84 104 105 115 32 105 115 32 110 101 119 32 108 105 110 101 46 
           

 從上面的運作結果可以看出: 1、Windows與Mac的結果一緻; 2、三種平台下,\n的實際結果是“回車” + “換行”; 3、Windows、Mac下的\r也是“回車” + “換行”,但是Linux下,\r卻是回到目前行首,會抹到以前的輸出結果;

繼續閱讀