您的位置:首页 > 其它

readLine() 和 "\r","\n" 问题

2015-08-30 17:38 204 查看
很多输入流中都有一个函数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来读的话,则没有这种情况,它会按字节读取。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: