[英]How does java.io.InputStream.read() work?
Why does this : 为什么这样:
import java.io.*;
class ioTest2 {
public static void main(String args[])throws IOException{
int b;
while( (b = System.in.read() ) != -1)
System.out.print((char)b);
}
}
work as expected,ie print exactly what you type, and this: 按预期工作,即完全打印您键入的内容,并且:
import java.io.*;
class ioTest2 {
public static void main(String args[])throws IOException{
int b;
while( (b = System.in.read() ) != -1)
System.out.print(b);
}
}
does not? 才不是? Why do I have cast
b
to a character to make the code correct? 为什么我将
b
转换为字符以使代码正确?
The read()
method returns an int
that stores the next byte that is read from the stream. read()
方法返回一个int
,该值存储从流中读取的下一个字节。 You need to cast it to a char
, or otherwise the int
value will be printed. 您需要将其
char
转换为char
,否则将打印int
值。
If you type "ABCD", then without casting, then the println(int)
method is called ( System.out
is a PrintStream
), and the values of the bytes are printed. 如果键入“ ABCD”,则不进行强制转换,则将调用
println(int)
方法 ( System.out
是PrintStream
),并打印字节的值。
B D
vv vv
65666768
^^ ^^
A C
If you cast it to a char
, then a different overloaded method, println(char)
is called, which knows to print the character specified, so it "works" (echoes to you the characters you typed). 如果将其
char
转换为char
,则将调用另一个不同的重载方法println(char)
,该方法知道将打印指定的字符,因此它可以“工作”(回显您键入的字符)。
The read()
method returns an integer , or -1 if the end of stream has been reached. read()
方法返回一个整数 ,如果已到达流的末尾,则返回 -1。
A char
, or character, is a primitive type , and can be represented as a number. char
或字符是原始类型 ,可以表示为数字。 Since you cast the integer to a character, it's represented on screen. 由于您将整数转换为字符,因此它将在屏幕上显示。
System.out.print((char)b)
calls a different method from System.out.print(b)
. System.out.print((char)b)
调用与System.out.print(b)
不同的方法 。 They do different things. 他们做不同的事情。
Which method to call is not just determined by the name, but by the name and the type signature (ie, by the types of the arguments). 调用哪种方法不仅取决于名称,还取决于名称和类型签名 (即,参数的类型)。 Different methods can have the same name, so long as they have different argument lists.
不同的方法可以具有相同的名称,只要它们具有不同的参数列表即可。
Read the JavaDoc: 阅读JavaDoc:
http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#print%28int%29 http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#print%28int%29
Versus 与
http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#print%28char%29 http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#print%28char%29
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.