Why Java OutputStream.write() Takes Integer but Writes Bytes

后端 未结 5 675
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 07:01

I am writing an OutputStream, just noticed this in the OutputStream interface,

   public abstract void write(int b) throws IOException;

Thi

5条回答
  •  春和景丽
    2020-12-05 07:13

    The Java IOStream classes have been a part of Java since 1.0. These classes only deal with 8 bit data. My guess is that the interface was designed like this so that the one write(int b) method would be called for int, short, byte, and char values. These are all promoted to an int. In fact since most JVMs run on 32 bit machines, the int primitive is the most efficient type to deal with. The compiler is free to store types such as bytes using 32 bits anyway. Interestingly, byte[] really is stored as a sequence of 8 bit bytes. This makes sense since an array could be quite large. However in the case of single primitive values such as int or byte, the ultimate space occupied at runtime doesn't really matter as long as the behavior is consistent with the spec.

    More background:

    http://www.java-samples.com/showtutorial.php?tutorialid=260

    The assumption for the IOStream classes is that the caller only really cares about lowest 8 bits of data even when passing in an int. This is fine as long the caller knows it is really dealing with bytes, but it becomes a problem when underlying data is really text that uses some other character encoding such as multi-byte Unicode. This is why the Reader classes were introduced way back with Java 1.1. If you care about text data and performance, the IOStream classes are faster, but the Reader classes are more portable.

提交回复
热议问题