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来读的话,则没有这种情况,它会按字节读取。

转载于:https://www.cnblogs.com/chaiwentao/p/4771231.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值