In Java: why do some Stream methods accept int instead of byte or even char?

Why do some methods that write bytes/charsfor threads take intinstead byte/char??

Someone told me in the case of int instead char: because charin java it is only 2 bytes long, and this is normal with most characters that are already in use, but for certain character characters (chines or something else) the character is represented in more than 2 bytes, and so we use int instead.

How close is this explanation to the truth?

EDIT: I use the word streamto represent binary and character streams (not just binary streams)

Thank.

+3
source share
6 answers

Someone told me in the case of int instead of char: because char in java has a length of only 2 bytes, which is ok with most character characters that are already in use, but for certain character characters (Chinese or any other) the character appears more than in 2 bytes, and therefore we use int instead.

Assuming that at this moment you are talking specifically about a method Reader.read(), the statement from "someone" that you recounted is actually incorrect .

, Unicode 65535 Java char. API Reader Java char ( -1), Unicode. javadoc.

( ) Unicode, 65535, read(), . , , UTF-16; Java char, . , , Java String, StringBuilder StringBuffer; UTF-16... .

, Reader.read() int a char, -1, , . , InputStream.read() int a byte.

, , Java , read() , " ". , ( ) ( ). , , / . , , .

( 16- API Reader read(char[], ...). 65535, ?)

DataOutputStream.writeChar(int) . javadoc , 2 . .

, . , (4957024), "11-, " :

" , , ".

... , , , .

, , .

+5

, , , , InputStream.read()? , , , -1. 257 , .

, , .

+3

.

-, , , , read() int, , write() int, :

int read = in.read();
if ( read != -1 )
   out.write(read);
//vs
   out.write((byte)read);

-, :

//write a char (big-endian)
char c;
out.write(c >> 8);
out.write(c);

//vs
out.write( (byte)(c >> 8) );
out.write( (byte)c );
+2

, - 0x10FFFF, char. , - 16 . OutputStream.write(int) Writer. write (int) 16 .

0

Java . , Stream Writer.

Writer write(int) ( 16 , int, , - ), write(char[]) write(String).

0

possibly to be symmetric with the read () method, which returns an int. nothing serious.

0
source

Source: https://habr.com/ru/post/1752530/


All Articles