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"。
例子:
输出的结果为:
readLine 读出后的长度: 5 readLine读的结果: hello
可以看出,readLine函数会自动截取"\r","\n"之前的字符串。
输出结果:
h
e
l
l
o
end!
这里看出来如果用read来读的话,则没有这种情况,它会按字节读取。
如果我们是从控制台读入的话,我们也许没有想过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来读的话,则没有这种情况,它会按字节读取。
相关文章推荐
- linux查看cpu、内存、版本信息
- Powershell 技巧 查找一个字符串中的子串
- 工作第一周Oracle函数总结
- poj_1084 剪枝-IDA*
- C语言中的setlinebuf()、utmpname()、rewind函数使用
- Powershell技巧1 抓取执行过程中的错误信息
- 树莓派详细介绍
- AsyncTaskLoader设计原理大揭秘
- PHP常用的文件操作函数集锦
- Linux下*.tar.gz文件解压缩命令
- h5页面-1
- Log4j入门学习
- background-position 用法详细介绍
- android中的Notification(通知)
- python3 爬取豆瓣妹子
- AsyncTaskLoader设计原理大揭秘
- 谈谈我对软件工程的理解和对它的问题
- Python教程
- JAVA语言基础和软件测试基础的学习
- iOS用UIScorllView实现两指缩放功能