很多输入流中都有一个函数readLine(),我们也经常使用这个函数,但有时如果不认真考虑,这个函数也会带来一些小麻烦。
如果我们是从控制台读入的话,我们也许没有想过readLine函数到底是根据" "," "中的哪一个来截取字符串,因为一般计算机的实现时enter键按下后对应的既有" "," ";
补充说明一下:" "是把光标移到一行的开头," "是换到下一行,不同系统处理方式不一样,Unix系统中" "会移到下一行的开头,Windows则是表面意思。Mac的" "则是回到开头,并移到下一行。
根据我的测试,readLine返回的字符串中不包含结尾的" "," "。
例子:
String line = "hello "; 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函数会自动截取" "," "之前的字符串。
String line = "hello "; 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来读的话,则没有这种情况,它会按字节读取。