Java: InputStream read() returns a byte bigger than 127?

前端 未结 1 804
忘掉有多难
忘掉有多难 2020-12-21 06:35

I\'ve this code:

InputStream is = socket.getInputStream();
int b;
while ((b = is.read()) != -1)
{
   System.out.println(b);
}

A byte its ra

相关标签:
1条回答
  • 2020-12-21 07:06

    Actually read returns an integer..

    public abstract int read() throws IOException
    

    so it's implictly casted to be unsigned byte by storing it in an int.

    As stated in documentation:

    Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

    Think about the fact that if it's a signed byte then -1 couldn't be used as end of stream value.

    For OutputStream you have

    public abstract void write(int b) throws IOException
    

    and as stated by documentation implementation will take 8 low order bits of the integer passed..

    0 讨论(0)
提交回复
热议问题