readLine() 和 "\r","\n" 問題


很多輸入流中都有一個函數readLine(),我們也經常使用這個函數,但有時如果不認真考慮,這個函數也會帶來一些小麻煩。

如果我們是從控制台讀入的話,我們也許沒有想過readLine函數到底是根據"\r","\n"中的哪一個來截取字符串,因為一般計算機的實現時enter鍵按下后對應的既有"\r","\n";

補充說明一下:"\r"是把光標移到一行的開頭,"\n"是換到下一行,不同系統處理方式不一樣,Unix系統中"\n"會移到下一行的開頭,Windows則是表面意思。Mac的"\r"則是回到開頭,並移到下一行。

根據我的測試,readLine返回的字符串中不包含結尾的"\r","\n"。

例子:

String line = "hello\r";
        
        OutputStream out = new FileOutputStream(".//out.txt");
        
        out.write(line.getBytes());
        
        InputStream in = new FileInputStream(".//out.txt");
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String str = reader.readLine();
        
        System.out.println("readLine 讀出后的長度: "+str.length()+"     readLine讀的結果: "+str);

輸出的結果為:

readLine 讀出后的長度: 5     readLine讀的結果: hello

可以看出,readLine函數會自動截取"\r","\n"之前的字符串。

String line = "hello\r";
        
        OutputStream out = new FileOutputStream(".//out.txt");
        
        out.write(line.getBytes());
        
        InputStream in = new FileInputStream(".//out.txt");
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        //String str = reader.readLine();
        
        /*System.out.println("readLine 讀出后的長度: "+str.length()+"     readLine讀的結果: "+str);*/
        
        byte[] b = new byte[100];
        
        in.read(b,0,line.length());
        
        for(int i = 0; i<line.length(); i++){
            System.out.println((char)b[i]);
        }
        System.out.println("end!");

輸出結果:

h
e
l
l
o


end!

這里看出來如果用read來讀的話,則沒有這種情況,它會按字節讀取。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM